我正在使用一个处理程序来启动一个asynctask,但是当这样做时,我的应用程序崩溃。我被卡住的原因是因为如果我通过其他任何东西(例如onClickListener)启动了Asynctask,那么我可以一次又一次地运行它,并且它每次都能完美运行。只要我从我的处理程序执行asynctask,它立即崩溃与NullPointerException异常的应用程序。asynctask在处理程序中调用时不会收到arraylist
我的处理程序看起来像这样
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();
}
});
}
};
下面是从应用程序的堆栈跟踪的部分显示异常
Caused by: java.lang.NullPointerException
at badams.android.app.fragments.MainMenu_NearbyFragment$sortNearby.doInBackground(MainMenu_NearbyFragment.java:100)
我的代码
线100是下的AsyncTask第一线doInBackground
protected String doInBackground(String... args) {
for (int i = 0; i < global.places.size(); i++) { //this is line 100
我知道例外情况更多可能来自“global.places.size()”可能为空,但我坚持为什么只有在从处理程序调用时才这样做,因为如果我从代码的任何其他部分启动任务,它工作正常。
EDIT
按照要求通过@Raghunandan,这里是从doInBackground在我的AsyncTask,其计算为 “地方” 和用户之间的距离的整个代码块:
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;
}
编辑2
全局是一个扩展应用程序的类,并在活动中定义如下:
global = (ApplicationGlobal) getActivity().getApplicationContext();
post asynctask code – Raghunandan 2013-04-18 03:36:08
@Raghunandan用doInBackground的整个代码块更新了问题。 – Badams 2013-04-18 03:46:52
asycntask应该加载到UI线程上。 http://developer.android.com/reference/android/os/AsyncTask.html。检查主题线程规则 – Raghunandan 2013-04-18 03:48:28