我已經創建了活動,應該在用戶單擊按鈕後返回GeoPoint數組。執行http請求和解析答案的代碼被提取到AsyncTask。在onPostExecute()
方法我已經分配overlayList
與doInBackground()
方法的返回值,但它沒有工作,AsyncTask僅在使用get()方法後返回值
overlayList.size()
thows一個NullPointerException異常。這是我原來的代碼:
public class MyActivity extends Activity {
Button bt;
TextView tv1;
List<GeoPoint> overlayList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt = (Button) findViewById(R.id.button);
tv1 = (TextView) findViewById(R.id.textView);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String query = "http://maps.googleapis.com/maps/api/directions/json?origin=bla-bla&destination=bla-bla&sensor=false";
Request mat = new Request();
mat.execute(query);
if (overlayList.size() > 0){
tv1.setText("List is OK!");
}
}
});
}
private class Request extends AsyncTask<String, Void, ArrayList<GeoPoint>> {
@Override
protected ArrayList<GeoPoint> doInBackground(String... params) {
return parse(connect(params[0]));
}
@Override
protected void onPostExecute(ArrayList<GeoPoint> geoPoints) {
super.onPostExecute(geoPoints);
overlayList = geoPoints;
}
public JSONObject connect(String url) {
...
}
public ArrayList<GeoPoint> parse(JSONObject jsonObject) {
...
}
}
但是,如果我將修改我的OnClickListener
以這樣的方式:
HttpRequest mat = new HttpRequest();
mat.execute(query);
try {
overlayList = mat.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
列表中的一切會確定,overlayList.size()
返回大小。所以,我的問題 - 爲什麼onPostExecute()
方法不初始化我的列表?
overlayList.add(geoPoints); – Raghunandan 2013-04-11 15:37:29
不要調用'super.onPostExecute(geoPoints);'。 – 2013-04-11 15:38:53
可以發表你的解析(連接(...))代碼 – Raghunandan 2013-04-11 15:42:15