使用回調將解析查詢包裝在AsyncTask
中,並在線程池上執行以使任務能夠並行運行。
實施例:
public class MainActivity extends AppCompatActivity implements OnTaskCompleted {
@Override
public void onTaskCompleted(List<ParseObject> response) {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
new FetchParseQueryTask(MainActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new PagingOptions(0, 200));
new FetchParseQueryTask(MainActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new PagingOptions(1, 200));
new FetchParseQueryTask(MainActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new PagingOptions(2, 200));
}
}
回調:
public interface OnTaskCompleted {
void onTaskCompleted(List<ParseObject> response);
}
樣品實施FetchParseQueryTask
類:
public class FetchParseQueryTask extends AsyncTask<PagingOptions, Void, List<ParseObject>> {
private OnTaskCompleted mTaskCompleted;
public FetchParseQueryTask(OnTaskCompleted activityContext){
mTaskCompleted = activityContext;
}
@Override
protected List<ParseObject> doInBackground(PagingOptions... params) {
PagingOptions pagingOptions = params[0];
ParseQuery<ParseObject> query = ParseQuery.getQuery("TABLE_NAME");
query.setLimit(pagingOptions.getLimit());
query.setSkip(pagingOptions.getPage() * pagingOptions.getLimit());
try {
return query.find();
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(List<ParseObject> result) {
super.onPostExecute(result);
if (mTaskCompleted != null) {
mTaskCompleted.onTaskCompleted(result);
}
}
}
PagingOptions
類:
public class PagingOptions {
private int mPage;
private int mLimit;
public PagingOptions(int page, int limit)
{
mPage = page;
mLimit = limit;
}
public int getPage() {
return mPage;
}
public void setPage(int mPage) {
this.mPage = mPage;
}
public int getLimit() {
return mLimit;
}
public void setLimit(int mLimit) {
this.mLimit = mLimit;
}
}
親愛的克萊夫,非常感謝。我添加了一個帶有回調的構造函數到FetchParseQueryTask來獲得結果。這是正確的,對嗎? –
是的,我已經用示例回調更新了答案 –