NullPointerException error on Implementing Location API on J2me - exception

I am trying to implement jsr-179 APi into Nokia Symbian phone for periodic location update using setLocationListener through J2me. In emulator it is working fine. While I installed Midlet on the device nokia 5230, it is given NullPointerException and the application is automatically terminating. What might be possible causes?
Below is my class, I am instantiating object for this class on a form in netbeans
class MovementTracker implements LocationListener {
LocationProvider provider;
Location lastValidLocation;
UpdateHandler handler;
boolean done;
public MovementTracker() throws LocationException
{
done = false;
handler = new UpdateHandler();
new Thread(handler).start();
//Defining Criteria for Location Provider
/*
Criteria cr = new Criteria();
cr.setHorizontalAccuracy(500);
*/
//you can place cr inside getInstance
provider = LocationProvider.getInstance(null);
//listener,interval,timeout,int maxAge
//Passing -1 selects default interval
// provider.setLocationListener(MovementTracker.this, -1, -1, -1);
provider.setLocationListener(MovementTracker.this, -1, 30000, 30000);
}
public void locationUpdated(LocationProvider provider, Location location)
{
handler.handleUpdate(location);
batteryLevel = System.getProperty("com.nokia.mid.batterylevel");
sn = System.getProperty("com.nokia.mid.networksignal");
localTime = System.currentTimeMillis();
Send_Location();
}
public void providerStateChanged(LocationProvider provider, int newState)
{
}
class UpdateHandler implements Runnable
{
private Location updatedLocation = null;
// The run method performs the actual processing of the location
public void run()
{
Location locationToBeHandled = null;
while (!done)
{
synchronized(this)
{
if (updatedLocation == null)
{
try
{
wait();
}
catch (Exception e)
{
// Handle interruption
}
}
locationToBeHandled = updatedLocation;
updatedLocation = null;
}
// The benefit of the MessageListener is here.
// This thread could via similar triggers be
// handling other kind of events as well in
// addition to just receiving the location updates.
if (locationToBeHandled != null)
processUpdate(locationToBeHandled);
}
try
{
Thread.sleep(10000); //Sleeps for 10 sec & then sends the data
}
catch (InterruptedException ex)
{
}
}
public synchronized void handleUpdate(Location update)
{
updatedLocation = update;
notify();
}
private void processUpdate(Location update)
{
latitude = update.getQualifiedCoordinates().getLatitude();
longitude = update.getQualifiedCoordinates().getLongitude();
altitude = update.getQualifiedCoordinates().getAltitude();
}
}
}

public MovementTracker() throws LocationException
...
I have not written any code for handling LocationException.
No code is very dangerous practice, just search the web for something like "java swallow exceptions".
It is quite possible that because of implementation specifics Nokia throws LocationException where emulator does not throw it. Since you don't handle exception this may indeed crash you midlet at Nokia - and you wouldn't know the reason for that because, again, you have written no code to handle it.
How can I catch that exception?
The simplest thing you can do is to display an Alert with exception message and exit the midlet after user reads and dismisses alert

Related

Wifi is not detected sometimes on android devices with OS Android 8.1 and above

When a smartphone gets connected to wifi without internet, the job scheduler does not detect the wifi change and onAvailable method is not called sometimes. This issue is observed in android 8.1 OS and above smartphones.
This the code snippet used to detect the wifi connection.
The job is created on launch of the app in the launcher activity.
try {
ComponentName componentName = new ComponentName(this, JobSchedulerWifi.class);
JobInfo jobInfo = new JobInfo.Builder(12, componentName)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true)
.build();
JobScheduler jobScheduler = (JobScheduler)getSystemService(JOB_SCHEDULER_SERVICE);
int resultCode = jobScheduler.schedule(jobInfo);
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Log.d("XXX", "Wifi_Job scheduled!"+jobInfo.getId());
} else {
Log.d("XXX", "Wifi_Job not scheduled");
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
public class JobSchedulerService extends JobService {
ConnectivityManager connectivityManager;
ConnectivityManager.NetworkCallback networkCallback;
BroadcastReceiver connectivityChange;
Context cont;
private boolean jobCancelled=false;
#Override
public boolean onStartJob(final JobParameters job) {
Log.d("Job", Build.VERSION.SDK_INT+"Job - Job created"+Build.VERSION_CODES.LOLLIPOP);
cont=this;
connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
cont=this;
connectivityManager.registerDefaultNetworkCallback(networkCallback = new ConnectivityManager.NetworkCallback() {
#Override
public void onAvailable(Network network) {
// super.onAvailable(network);
WifiManager wifiManager = (WifiManager) cont.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifi = wifiManager.getConnectionInfo();
String wificonnect =wifi.getSSID();
wificonnect = wificonnect.substring(1, wificonnect.length() - 1);
Log.i("job", "Default -> Internet Network Available"+wificonnect);
}
Have you thought about using WorkManger?
WorkManager, part of Android X is supported back to API level 14 and makes detecting and running code on connection change a simple task.
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val myWorkRequest =
OneTimeWorkRequestBuilder<MyWorker>()
.setConstraints(constraints)
.build()
WorkManager.getInstance(MyApplication.context).enqueue(myWorkRequest)
And the class that will be executed when the connection is detected:
class MyWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
override fun doWork(): Result {
doThis()
return Result.success()
}
private fun doThis() {
Log.d("ASDF", "::onReceive")
}
}
Additional resources:
Current library
Google documentation

Nested Transactions with MySQL and Entity Framework Core

I'm using MySQL with EF Core. I am currently using Pomelo Provider for MySQL. I need to implement Unit Of Work Pattern for transactions. I have a Service which calls two methods in repository. I am not able to implement nested transactions. This is how my method in service looks now:
public void methodA(param)
{
using (TransactionScope tx = new
TransactionScope(TransactionScopeOption.Required))
{
repo1.save(data1);
repo2.save(data2);
tx.complete();
}
}
This is how save method in repo1 is implemented
private readonly UserDbContext appDbContext;
public repo1(UserDbContext _appDbContext)
{
appDbContext = _appDbContext;
}
public void save(User entity)
{
var dbset = appDbContext.Set<User>().Add(entity);
appDbContext.SaveChanges();
}
This is how save method in repo2 is implemented
private readonly UserDbContext appDbContext;
public repo2(UserDbContext _appDbContext)
{
appDbContext = _appDbContext;
}
public void save(UserRole entity)
{
var dbset = appDbContext.Set<UserRole>().Add(entity);
appDbContext.SaveChanges();
}
I am getting the following error while running method in service:
Error generated for warning 'Microsoft.EntityFrameworkCore.Database.Transaction.AmbientTransactionWarning: An ambient transaction has been detected. The current provider does not support ambient transactions. See http://go.microsoft.com/fwlink/?LinkId=800142'. This exception can be suppressed or logged by passing event ID 'RelationalEventId.AmbientTransactionWarning' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.
This is how I registered UserDbContext in Startup.cs
services.AddDbContext<UserDbContext>(options => options.UseLazyLoadingProxies().UseMySql("Server = xxxx; Database = xxx; Uid = xx;ConnectionReset=True;", b => b.MigrationsAssembly("AssemblyName")));
I even tried adding a middleware which starts transaction at the begining of request and commits/rollbacks during the response . But still I am not able to manage nested transactions.
This is how my middleware looks:
public class TransactionPerRequestMiddleware
{
private readonly RequestDelegate next_;
public TransactionPerRequestMiddleware(RequestDelegate next)
{
next_ = next;
}
public async Task Invoke(HttpContext context, UserDbContext
userDbContext)
{
var transaction = userDbContext.Database.BeginTransaction(
System.Data.IsolationLevel.ReadCommitted);
await next_.Invoke(context);
int statusCode = context.Response.StatusCode;
if (statusCode == 200 || statusCode==302)
{
transaction.Commit();
}
else
{
transaction.Rollback();
}
}
}
Can anyone help me please?

Try-Catch not working for controller to class library [Debugger Mode]

I am running dotnet core 2.* and as the title mentions I have trouble getting my try catch to work when calling from API. And before anyone comments I am also running middle-ware to catch any exceptions. It too doesn't perform as expected
Addinional Information:
The Two Classes are in different namespaces/projects
Queries.Authentication is static.
They are both in the same solution
Controller:
[AllowAnonymous]
[HttpPost]
public string Login([FromBody] AuthRequest req)
{
// See if the user exists
if (Authenticate(req.username, req.password))
{
try {
// Should Fail Below
UserDetails ud = Queries.Authentication.GetUser(req.username);
} catch (RetrievalException e){ }
catch (Exception e){ } // Exception Still Comes Through
}
}
Queries.Authentication.GetUser Code:
public static class Authentication {
public static UserDetails GetUser (string username)
{
// Some Code
if (details.success)
{
// Some Code
}
else
{
throw new RetrievalException(details.errorMessage); // This is not caught propperly
}
}
}
Retrieval Exception:
public class RetrievalException : Exception
{
public RetrievalException()
{
}
public RetrievalException(String message)
: base(message)
{
}
public RetrievalException(String message, Exception inner)
: base(message, inner)
{
}
}
EDIT: Adding Middleware Code Here as per request:
public class CustomExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
HttpStatusCode status = HttpStatusCode.InternalServerError;
String message = String.Empty;
var exceptionType = context.Exception.GetType();
if (exceptionType == typeof(UnauthorizedAccessException))
{
message = "Unauthorized Access";
status = HttpStatusCode.Unauthorized;
}
else if (exceptionType == typeof(NullReferenceException))
{
message = "Null Reference Exception";
status = HttpStatusCode.InternalServerError;
}
else if (exceptionType == typeof(NotImplementedException))
{
message = "A server error occurred.";
status = HttpStatusCode.NotImplemented;
}
else if (exceptionType == typeof(RSClientCore.RetrievalException))
{
message = " The User could not be found.";
status = HttpStatusCode.NotFound;
}
else
{
message = context.Exception.Message;
status = HttpStatusCode.NotFound;
}
context.ExceptionHandled = true;
HttpResponse response = context.HttpContext.Response;
response.StatusCode = (int)status;
response.ContentType = "application/json";
var err = "{\"message\":\"" + message + "\",\"code\" :\""+ (int)status + "\"}";
response.WriteAsync(err);
}
}
App Config:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} else
{
app.UseExceptionHandler();
}
...
}
Service Config:
public void ConfigureServices(IServiceCollection services)
{
// Add Model View Controller Support
services.AddMvc( config =>
config.Filters.Add(typeof (CustomExceptionFilter))
);
UPDATE: After playing around with it I noticed that even though my program throws the exception, if I press continue the API controller then handles it as if the exception was never thrown (as in it catches it and does what I want). So I turned off the break on Exception setting, this fixed it in debugger mode. However this the break doesn't seem to be an issue when I build/publish the program. This makes me think it is definitely a issue with visual studio itself rather than the code.
When you set ExceptionHandled to true that means you have handled the exception and there is kind of no error anymore. So try to set it to false.
context.ExceptionHandled = false;
I agree it looks a bit confusing, but should do the trick you need.
Relevant notes:
For those who deal with different MVC and API controller make sure you implemented appropriate IExceptionFilter as there are two of them - System.Web.Mvc.IExceptionFilter (for MVC) and System.Web.Http.Filters.IExceptionFilter (for API).
There is a nice article about Error Handling and ExceptionFilter Dependency Injection for ASP.NET Core APIs you could use as a guide for implementing exception filters.
Also have a look at documentation: Filters in ASP.NET Core (note selector above the left page menu to select ASP.NET Core 1.0, ASP.NET Core 1.1,ASP.NET Core 2.0, or ASP.NET Core 2.1 RC1). It has many important notes and explanations why it works as it does.

Spring SSEEmitter Getting Completed Mid-way

I am new to Server Sent Events but not to Spring.
Have made a controller which gets triggered from a button on the UI which initiates SSEEmitter and passed that to another thread which in loop sends message to UI after each 4 seconds.
SO far i am running a loop of 10 which sleeps for 4 seconds each but suddenly around iteration of 6 or 7th loop, I get exception "Exception in thread "Thread-4" java.lang.IllegalStateException: ResponseBodyEmitter is already set complete"..
Hence, event source again re-establishes the connection i.e. calls the controller method again which certainly i do not want.
I am here trying a simple thing.. User subscribes by clicking on the button..
Server send response 10 or 20 whatever times to the browser. And as far as I think this is what SSE created for.
Code below.:
#RequestMapping("/subscribe")
public SseEmitter subscribe() {
SseEmitter sseEmitter = new SseEmitter();
try {
sseEmitter.send("Dapinder");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Runnable r = new AnotherThread(sseEmitter);
new Thread(r).start();
return sseEmitter;
}
public class AnotherThread implements Runnable {
private SseEmitter sseEmitter;
public AnotherThread(SseEmitter sseEmitter) {
super();
this.sseEmitter = sseEmitter;
}
#Override
public void run() {
SseEventBuilder builder = SseEmitter.event();
builder.name("dapEvent");
for (int i = 0; i < 10; i++) {
builder.data("This is the data: " + i +" time.");
try {
//sseEmitter.send(builder);
sseEmitter.send("Data: "+i);
//sseEmitters.get(1L).send("Hello");
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
sseEmitter.complete();
}
public SseEmitter getSseEmitter() {
return sseEmitter;
}
public void setSseEmitter(SseEmitter sseEmitter) {
this.sseEmitter = sseEmitter;
}
}
function start() {
var eventSource = new EventSource("http://localhost:8080/HTML5SSE/springSSE/subscribe"); // /springSSE/connect
eventSource.onmessage = function(event) {
document.getElementById('foo').innerHTML = event.data;
};
}
<button onclick="start()">Subscribe</button>
Your builder is not being used; you create and configure a builder, but then you send a plain message with 'sseEmitter.send' directly. Try this:
sseEmitter.send(SseEmitter.event().name("dapEvent").data("This " + i +" time.");
One more thing: Why do you call the send method already in the subscribe method? At this point in time, the SseEmitter has not been returned. Is this message coming through to the client?
Here is an excellent article explaining SSE from the JavaScript perspective (not Spring). You will see here that you can cancel the event stream from the client by calling close on the stream. Combine this with an event listener, and you should have what you need:
var source = new EventSource('...');
source.addEventListener('error', function(e) {
if (e.currentTarget.readyState == EventSource.CLOSED) {
// Connection was closed.
} else {
// Close it yourself
source.close();
}
});
source.addEventListener('message', function(e) {
console.log(e.data);
});
Note: The article says e.readyState, however I think this is wrong. The received object e is an Event. You need to get the EventSource object from it like this: e.currentTarget.
You need to use the second constructor of SseEmitter which takes a Long timeout argument. Please refer the code below -
#RequestMapping("/subscribe")
public SseEmitter subscribe() {
SseEmitter sseEmitter = new SseEmitter(Long.MAX_VALUE) // for maximum timeout
Below is the copy of Java-doc of this constructor -
/**
* Create a SseEmitter with a custom timeout value.
* <p>By default not set in which case the default configured in the MVC
* Java Config or the MVC namespace is used, or if that's not set, then the
* timeout depends on the default of the underlying server.
* #param timeout timeout value in milliseconds
* #since 4.2.2
*/
I think the default timeout of SSE connection in Tomcat is 40 seconds. Not sure though.

How to use BroadcastReceiver with MvvmCross when app is not running

I'm working in an Android application and I'm having some trouble using the BroadcastReceiver with MvvmCross. I have the broadcast to receive messages from GCM (Push Notification) and then i create an IntentService that would do something when a message is received.
In my IntentService I use a Mvx.Resolve to make some calls to the Core project. Since the app is not running it throws an exception that it was not found (when trying to use Mvx.Resolve).
I tried finding a solution in the web and the closest i got was: How do I initialize the MvvmCross framework without a splash Activity? .
So I tried using it but I received another exception.
Android.Content.ReceiverCallNotAllowedException: Exception of type 'Android.Content.ReceiverCallNotAllowedException' was thrown
I saw this was happening when trying to create a receiver inside another receiver.
My broadcast is the following (using the code from the stack above):
[BroadcastReceiver(Permission= "com.google.android.c2dm.permission.SEND")]
[IntentFilter(new string[] { "com.google.android.c2dm.intent.RECEIVE" }, Categories = new string[] { "MyPackage" }, Priority = (int)IntentFilterPriority.HighPriority)]
[IntentFilter(new string[] { "com.google.android.c2dm.intent.REGISTRATION" }, Categories = new string[] { "MyPackage" }, Priority = (int)IntentFilterPriority.HighPriority)]
[IntentFilter(new string[] { "com.google.android.gcm.intent.RETRY" }, Categories = new string[] { "MyPackage" }, Priority = (int)IntentFilterPriority.HighPriority)]
public class GCMBroadcastReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
var setup = MvxAndroidSetupSingleton.EnsureSingletonAvailable(context);
setup.EnsureInitialized();
GCMIntentService.RunIntentInService(context, intent);
SetResult(Result.Ok, null, null);
}
}
My IntentService:
[Service]
public class GCMIntentService : IntentService
{
static PowerManager.WakeLock sWakeLock;
static object LOCK = new object();
public static void RunIntentInService(Context context, Intent intent)
{
lock (LOCK)
{
if (sWakeLock == null)
{
// This is called from BroadcastReceiver, there is no init.
var pm = PowerManager.FromContext(context);
sWakeLock = pm.NewWakeLock(WakeLockFlags.Partial, "GCM Broadcast Receiver");
}
}
sWakeLock.Acquire();
intent.SetClass(context, typeof(GCMIntentService));
context.StartService(intent);
}
protected override void OnHandleIntent(Intent intent)
{
try
{
var context = this.ApplicationContext;
var action = intent.Action;
if (action.Equals("com.google.android.c2dm.intent.REGISTRATION"))
{
HandleRegistration(context, intent);
}
else if (action.Equals("com.google.android.c2dm.intent.RECEIVE"))
{
HandleMessage(context, intent);
}
}
finally
{
lock (LOCK)
{
//Sanity check for null as this is a public method
if(sWakeLock != null)
{
sWakeLock.Release();
}
}
}
}
private void HandleRegistration(Context context, Intent intent)
{
var registration = intent.GetStringExtra("registration_id");
if(intent.GetStringExtra("error") != null)
{
// Registration failed, should try again later.
}
else if(intent.GetStringExtra("unregistered") != null)
{
// Unregistered
}
else if(registration != null)
{
//Do registration
}
}
private void HandleMessage(Context context, Intent intent)
{
Task.Factory.StartNew(() =>
{
Mvx.Resolve<MyInterface>().DoSomething();
});
}
}
I read in that same stack overflow that if I was using only a simple Mvx.Resolve it would be easier to instantiate it by myself. The problem is that inside my method "DoSomething" it uses more Mvx.Resolves and I didn't want to change the core application because of the Android.
So I was wondering if there is any way to start the framework so that I would not have to change the Core or if the best way to deal with this would be changing the core.
Edit:
The Exception Trace is (I got this from the logcat since i can't debug an app that is not running):
Android.Content.ReceiverCallNotAllowedException: Exception of type 'Android.Content.ReceiverCallNotAllowedException' was thrown.
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () <0x00028>
at Android.Runtime.JNIEnv.CallObjectMethod (intptr,intptr,Android.Runtime.JValue[]) <0x000c3>
at Android.Content.ContextWrapper.RegisterReceiver (Android.Content.BroadcastReceiver,Android.Content.IntentFilter) <0x0018f>
at Thrust.Plugins.Network.Droid.NetworkService.OnNetworkChanged (System.Action`1<Thrust.Plugins.Network.NetworkStatus>) <0x00093>
at Chat.Core.App.Initialize () <0x00533>
at Cirrious.MvvmCross.Platform.MvxSetup.CreateAndInitializeApp (Cirrious.CrossCore.Plugins.IMvxPluginManager) <0x0005b>
at Cirrious.MvvmCross.Platform.MvxSetup.InitializeApp (Cirrious.CrossCore.Plugins.IMvxPluginManager) <0x00027>
at Cirrious.MvvmCross.Platform.MvxSetup.InitializeSecondary () <0x00133>
at Cirrious.MvvmCross.Platform.MvxSetup.Initialize () <0x0002b>
at Cirrious.MvvmCross.Droid.Platform.MvxAndroidSetupSingleton.EnsureInitialized () <0x0011b>
at Chat.Droid.GCM.GCMBroadcastReceiver.OnReceive (Android.Content.Context,Android.Content.Intent) <0x0002b>
at Android.Content.BroadcastReceiver.n_OnReceive_Landroid_content_Context_Landroid_content_Intent_ (intptr,intptr,intptr,intptr) <0x0007b>
at (wrapper dynamic-method) object.0daa077c-c2f5-4cd5-bcbc-bc391ce0b2c3 (intptr,intptr,intptr,intptr) <0x0004b>
--- End of managed exception stack trace ---
android.content.ReceiverCallNotAllowedException: BroadcastReceiver components are not allowed to register to receive intents
at android.app.ReceiverRestrictedContext.registerReceiver(ContextImpl.java:246)
at android.app.ReceiverRestrictedContext.registerReceiver(ContextImpl.java:235)
at chat.droid.gcm.GCMBroadcastReceiver.n_onReceive(Native Method)
at chat.droid.gcm.GCMBroadcastReceiver.onReceive(GCMBroadcastReceiver.java:28)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2659)
at android.app.ActivityThread.access$1800(ActivityThread.java:174)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1383)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5593)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
[ERROR] FATAL UNHANDLED EXCEPTION: Android.Content.ReceiverCallNotAllowedException: Exception of type 'Android.Content.ReceiverCallNotAllowedException' was thrown.