我有一个冻结我的应用程序的解析查询:
ParseQuery<ParseObject> query = new ParseQuery<>("Puzzle");
query.whereEqualTo("puzzle", "somePuzzle");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
ArrayList<Puzzle> listPuzzle = new ArrayList<>();
for (ParseObject object : objects) listPuzzle.add(new Puzzle(object));
ListView list = (ListView) findViewById(R.id.list_puzzle);
if (list != null && listPuzzle.size() != 0) {
AdapterPuzzle adapterPuzzle = new AdapterPuzzle(listPuzzle, ScreenPuzzle.this);
list.setAdapter(adapterPuzzle);
}
} else e.printStackTrace();
}
});
当我执行此查询时,活动会冻结几秒钟,直到我填充了ListView。
我测试了运行查询而没有方法中的内容&#34;完成&#34;它似乎运行顺利,所以我的猜测是我在&#34;完成&#34;方法是冻结活动,因为它可能做很多工作,特别是迭代器:
for (ParseObject object : objects) listPuzzle.add(new Puzzle(object));
有没有办法在后台运行此迭代器或所有这些操作?有什么方法可以避免这种冻结?
答案 0 :(得分:1)
尝试使用AsyncTask课程。它具有完全适合您任务的doInBackground方法。
修改强>
我为需要参考的人添加了我的代码解决方案:
public class ScreenPuzzle extends AppCompatActivity {
private ListView list;
private TextView textUnresolved;
private ProgressBar loading;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_puzzle);
list = (ListView) findViewById(R.id.list_puzzle);
textUnresolved = (TextView) findViewById(R.id.text_unresolved);
loading = (ProgressBar) findViewById(R.id.loading_rank);
ParseQuery<ParseObject> query = new ParseQuery<>("Puzzle");
query.whereEqualTo("puzzle", "somePuzzle");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) new BackgroundOperation(objects).execute();
else e.printStackTrace();
}
});
}
private class BackgroundOperation extends AsyncTask<Void, Void, ArrayList<Puzzle>> {
private List<ParseObject> objects;
private ArrayList<Puzzle> listPuzzle;
public BackgroundOperation(List<ParseObject> objects) { this.objects = objects; }
@Override
protected ArrayList<Puzzle> doInBackground(Void... voids) {
listPuzzle = new ArrayList<>();
for (ParseObject object : objects) listPuzzle.add(new Puzzle(object));
return listPuzzle;
}
@Override
protected void onPostExecute(ArrayList<Puzzle> listPuzzle) {
if (list != null && listPuzzle.size() != 0) {
final AdapterPuzzle adapterPuzzle = new AdapterPuzzle(listPuzzle, ScreenPuzzle.this);
list.setAdapter(adapterPuzzle);
} else textUnresolved.setVisibility(View.VISIBLE);
loading.setVisibility(View.GONE);
}
}
}