我有一个AsyncTask,它需要使用上下文(在onPostExecute中使用),并运行doInBackground从服务器返回一个对象的ArrayList。当我执行这个任务时,我可以看到doInBackground正常运行,但它没有将结果传递给onPostExecute。
经过长时间的搜索,我仍然找不到如何在AsyncTask中返回一个对象的ArrayList的答案。
以下是我在doInBackground中创建并在onPostExecute中使用的对象:
经过长时间的搜索,我仍然找不到如何在AsyncTask中返回一个对象的ArrayList的答案。
以下是我在doInBackground中创建并在onPostExecute中使用的对象:
public class ServerTimeCard {
public String eventNameInput;
Boolean isLocation, isImage, isVoice;
public ServerTimeCard(String eventNameInput, boolean isLocation, boolean isImage, boolean isVoice) {
this.eventNameInput = eventNameInput;
this.isLocation = isLocation;
this.isImage = isImage;
this.isVoice = isVoice;
}
}
我在onCreate
中执行AsyncTask
,代码为new LoadFriendCards(context).execute();
期望的输出结果:
doInBackground
应该返回一个ArrayList给onPostExecute
当前的输出结果:
onPostExecute
中的ArrayList<ServerTimeCard>
的大小为零,而在doInBackground
中相同的数组列表大小较大。
以下是AsyncTask
代码。
public class LoadFriendCards extends AsyncTask<Void, Void, ArrayList<ServerTimeCard>> {
Context context;
ArrayList<ServerTimeCard> result;
public LoadFriendCards(Context context) {
this.context = context;
}
@Override
protected ArrayList<ServerTimeCard> doInBackground(Void... voids) {
result = new ArrayList<ServerTimeCard>();
// ...a bunch of data retrieval goes on here...
// querying parse for object info
// adding a new object to the local ArrayList for all in db
for (String friend : friendsListNames) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("TestObject");
query.whereEqualTo("accountName", friend+"@gmail.com");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
for (ParseObject cardInfo : objects) {
ServerTimeCard item = new ServerTimeCard(
cardInfo.getString("eventName"),
cardInfo.getBoolean("isImage"),
cardInfo.getBoolean("isImage"),
cardInfo.getBoolean("isVoice"));
result.add(item);
Log.e("New item called: ", String.valueOf(item.eventNameInput));
Log.e("New size of array...", String.valueOf(result.size()));
}
} else {
Log.d("info", "Error: " + e.getMessage());
}
}
});
}
// returning the new ArrayList<ServerTimeCard> to onPostExecute
// PROBLEM: THE SIZE OF THE RESULT IS 0
Log.e("Size of passing array", String.valueOf(result.size()));
return result;
}
@Override
protected void onPostExecute(ArrayList<ServerTimeCard> result) {
// PROBLEM: This returns 0
Log.e("Data list size: ", String.valueOf(result.size()));
// trying to use all objects in the arraylist here but it doesn't work
// due to the size. Something isn't passing correctly.
}
}
Log.e 输出的 Logcat 日志:(该日志看起来调用了 doInBackground,然后是 onPostExecute,接着又是 doInBackground)
E/Size of passing array﹕ 0
E/Data list size:﹕ 0
E/New item called:﹕ yah
E/New size of array...﹕ 1
E/New item called:﹕ lplokolol
E/New size of array...﹕ 2
E/New item called:﹕ It works
E/New size of array...﹕ 3
已解决:我最初认为需要使用AsyncTask,但最终我将所有代码都删除并将其全部放入我的Main类中的方法中。在异步任务中同时运行太多东西,导致结构混乱。教训是:保持简单。
result.add(item);
之后添加日志以确保item != null
,并立即在添加后查看result.size()
。 - 323go