我在Android Async Task中遇到了一些问题。在我的MainActivity中,我正在调用GetEventAsyncTask,它将执行名为retrieveEventJSON的方法:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this;
public void onSingleTap(float x, float y) {
final Point point = mMapView.toMapPoint(x, y);
eventModel.setEventX(String.valueOf(point.getX()));
eventModel.setEventY(String.valueOf(point.getY()));
new MyAsyncTask(new MyAsyncTask.OnRoutineFinished() {
public void onFinish() {
CreateEvent.createEventDialog(context, point.getX(),
point.getY(), eventAddress); //this will be called after the task finishes
}
}).execute(eventModel);
}
});
new GetEventAsyncTask().execute();
}
在我的GetEventAsyncTask中,基本上我只是检索从JSON返回的数据并将它们保存到数组中:
public class GetEventAsyncTask extends AsyncTask<Event, Integer, Double> {
EventController eventCtrl = new EventController();
String eventAddress;
Event eventModel = new Event();
public interface OnRoutineFinished{ //interface
void onFinish();
}
private OnRoutineFinished mCallbacks;
public GetEventAsyncTask(OnRoutineFinished callback){ //constructor with interface
mCallbacks = callback;
}
public GetEventAsyncTask(){} //empty constructor to maintain compatibility
@Override
protected Double doInBackground(Event... params) {
try {
eventAddress = eventCtrl.getStreetAddressFromGeometry(eventModel.getEventX(), eventModel.getEventY());
eventCtrl.retrieveEventJSON();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Double result) {
if(mCallbacks !=null)
mCallbacks.onFinish(); //call interface on finish
}
protected void onProgressUpdate(Integer... progress) {
}
}
然后当导航抽屉项目被选中时,我正在调用map方法上的绘图标记,该方法接收我刚刚保存的数组:
case 0:
eventCtrl.plotEventOnMap(context);
break;
我试图打印出在retrieveJSON中检索到的数据,但它确实打印出来了。但不知何故,当我试图在地图上绘图时,它没有显示任何内容。我想知道我重叠或重新初始化某个对象的哪个部分?
奇怪的是,如果我将getEventAsyncTask放在MainActivity下,它就会运行并检索数据。但是,如果我将getEventAsyncTask作为单个类移出,它就会停止工作。我想知道为什么会这样?
提前致谢。