我正在使用一個處理程序來啓動一個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