我已经创建了活动,应该在用户单击按钮后返回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