我使用AsyncTask
进行后台处理,即我从服务器获取数据并存储在List
doInBackground()
方法中。我在onPostExecute()
中使用此存储的数据。
我遇到的问题是onPostExceute()
即使在执行doInBackground()
之前就已执行了。
有人可以建议可能出现的问题吗?
代码:
AsyncTask<Void, Void, Void> read= new AsyncTask<Void, Void, Void>() {
ProgressDialog progress= new ProgressDialog(LastData.this);
ArrayList<String> testData;
DBAdapter db;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progress.setTitle("Please Wait");
testData= new ArrayList<String>();
db= new DBAdapter(LastData.this);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setMessage("Fetching Data !!");
progress.show();
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
ParseQuery query = new ParseQuery("Details");
query.findInBackground(new FindCallback() {
public void done(List<ParseObject> dataList,
ParseException e) {
if (e == null) {
Log.d("Details", "Retrieved " + dataList.size()
+ " scores");
for (int idx = 0; idx < dataList.size(); idx++) {
data.add(dataList.get(idx).get("fname")
.toString());
}
} else {
System.out.println(e.getMessage());
}
for (int idx = 0; idx < data.size(); idx++) {
testData.add(data.get(idx));
}
System.out.println("size inside is " + testData.size());
}
});
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progress.dismiss();
Toast.makeText(LastData.this, "Size is "+testData.size(), Toast.LENGTH_LONG).show();
}
};
read.execute();
即使在Toast
方法出现之前,onPostExecute()
中的{p> doInBackground
内容也会显示。
答案 0 :(得分:1)
如果在onPostExceute
完成任务之前执行doInBackground
,则表示您可能正在asynchronous
内进行doInBackground
来电。请发布代码以获得更具体的答案。
修改强>
问题是findInBackground
异步运行,因此您不需要AsynTask来调用它。它已经运行而没有阻塞你的线程,FindCallback
会在找到它时被调用。因此,您需要删除AsyncTask并找到您调用read.execute(...)
的位置并将其替换为:
1)将onPreExecute()
和doInBackground()
的代码放在那里
2)将代码从onPostExecute
放到FindCallback()
示例:
/*...*/
progress.setTitle("Please Wait");
testData= new ArrayList<String>();
db= new DBAdapter(LastData.this);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setMessage("Fetching Data !!");
progress.show();
ParseQuery query = new ParseQuery("Details");
query.findInBackground(new FindCallback() {
public void done(List<ParseObject> dataList,
ParseException e) {
if (e == null) {
Log.d("Details", "Retrieved " + dataList.size()
+ " scores");
for (int idx = 0; idx < dataList.size(); idx++) {
data.add(dataList.get(idx).get("fname")
.toString());
}
} else {
System.out.println(e.getMessage());
}
for (int idx = 0; idx < data.size(); idx++) {
testData.add(data.get(idx));
}
System.out.println("size inside is " + testData.size());
progress.dismiss();
Toast.makeText(LastData.this, "Size is "+testData.size(), Toast.LENGTH_LONG).show();
}
});
/*...*/
答案 1 :(得分:0)
看起来像
query.findInBackground(new FindCallback() { ... }
是某种异步任务。我假设有一个方法
query.find()
是同步的。