Thursday, April 18, 2013

[android help] asynctask not getting arraylist when called from a handler


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:



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);
publishProgress(global.places.get(i));
}
return null;
}


.

stackoverflow.comm

No comments:

Post a Comment

Google Voice on T-Mobile? [General]

Google Voice on T-Mobile? So I recently switched from a GNex on Verizon to a Moto X DE on T-Mobile. I had always used Google Voice for my v...