I'm using a handler to start an asynctask but when doing so, my application crashes. The reason I am stuck is because if I start the asynctask via anything else (eg. onClickListener) then I can run it as many times, over and over again, and it works perfect every single time. As soon as I execute the asynctask from my handler, it immediately crashes the application with a NullPointerException.
My handler looks something like this
public Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
handler.post(new Runnable() {
@Override
public void run() {
new sortNearby().execute();
}
});
}
};
Here is part of the stack trace from the application showing the exception
Caused by: java.lang.NullPointerException
at badams.android.app.fragments.MainMenu_NearbyFragment$sortNearby.doInBackground(MainMenu_NearbyFragment.java:100)
Line 100 of my code is the first line in the asynctask under doInBackground
protected String doInBackground(String... args) {
for (int i = 0; i < global.places.size(); i++) { //this is line 100
I understand that the exception is more than likely coming from "global.places.size()" probably being null, but I am stuck on why its doing that only when called from the handler, as it works fine if I start the task from any other section of my code.
EDIT
As requested by @Raghunandan, here is the entire code block from doInBackground in my asynctask, which calculates the distance between a "place" and the user:
class sortNearby extends AsyncTask<String, Place, String> {
protected String doInBackground(String... args) {
for (int i = 0; i < global.places.size(); i++) { //THIS IS LINE 100
Location locationA = new Location("place");
locationA.setLatitude(global.places.get(i).getLatitude());
locationA.setLongitude(global.places.get(i).getLongitude());
Location locationB = new Location("user");
locationB.setLatitude(global.applicationLocationManager.getLatitude());
locationB.setLongitude(global.applicationLocationManager.getLongitude());
float dist = locationA.distanceTo(locationB);
dist = dist / 1000;
global.places.get(i).setDistance(dist);
}
return null;
}
EDIT 2
global is a class extending Application and is defined in the Activity like so:
global = (ApplicationGlobal) getActivity().getApplicationContext();
If the NullPointerException
is at line 100 then either global
or global.places
is returning null
.
Did you try debugging the same?
Debugging will help you follow what is happening.
Also from the handler I do not see how your doInBackground
method gets called?
Where is the global
variable defined? Where and when it gets initialized?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.