I have a gps class in my application. In the onLocationChanged method I am sending a handler message to my activity which is supposed to execute an asynctask. My asyntask runs fine on its own if I call it anywhere from the activity, but I keep getting a crash when it gets called via the handler. I'm sure it has to do with how I'm starting the task from the handler.
Here is my handler in my activity fragment which is supposed to start the async task
public Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.d("MainMenu_NearbyFragment", "handler recieved for on location changed");
if (!sortingPlaces) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
new sortNearby().execute();
}
});
}
}
};
Im sending the message to the handler from my onLocationChanged like this
public void onLocationChanged(Location location) {
new MainMenu_NearbyFragment().handler.sendEmptyMessage(0);
}
EDIT:
Heres a stack trace after running on an actual device. (The previous was running on emulator, this is a different message which I didnt realize at first).
java.lang.NullPointerException
at badams.android.alcology.fragments.MainMenu_NearbyFragment$1.handleMessage(MainMenu_NearbyFragment.java:43)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Line 43 is:
getActivity().runOnUiThread(new Runnable() {
The reason I am doing this is because I need to be able to detect locationChanged from activities not implementing the LocationListener. So the idea is that in onLocationChanged I am sending a message to my activity informing it to update. Perhaps this is the wrong way for me to approach this?