我在使用 asynctask 在我的云数据库中查询时遇到了一些问题。
由于查询响应延迟,我无法正确获得结果。获取 NULL。
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
this.mBox = new Box();
super.onCreate(savedInstanceState);
setContentView(R.layout.novomenu_layout);
InicializaAzure(); // init connection to azure mobile service
this.mPalletDao = new PalletDAO(this);
this.mBoxDao = new BoxDAO(this);
mBox = mBoxDao.AzureGetBoxById(1); // query the cloud database
}
BoxDAO.java
public Box AzureGetBoxById(final long id){
final Box[] box = new Box[1];
final boolean[] flag = {false};
new AsyncTask<Void, Void, Void>() {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(mContext);
pDialog.setMessage("Just a moment...");
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
try {
final MobileServiceList<Box> result = mBoxTable.where().field("id").eq(id).execute().get();
Box mBox = result.get(0);
box[0] = mBox;
} catch (Exception exception) {
//createAndShowDialog(exception, "Error");
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
flag[0] = true;
}
}.execute();
return box[0];
//return null;
}
在异步任务完成之前,我总是得到 NULL。但我需要同时得到结果。 我该如何解决这个问题?我搜索过 asynctask 但没有找到类似的内容。
谢谢。
最佳答案
您的代码是正确的,并且工作正常。但是,如果你想让结果在UI显示的同时显示,使用asynctask就无法轻松解决。
根据我的经验,有两种方法可以帮助解决这个问题。
去掉asynctask代码,使用sync方法获取数据,但会导致UI挂起,不推荐。
使用
MobileServiceSyncTable
启用离线同步即可解决。
有一个示例文档 https://azure.microsoft.com/en-us/documentation/articles/mobile-services-android-get-started-offline-data/帮助将离线数据同步添加到您的应用中。
您也可以观看视频来学习,请移步http://channel9.msdn.com/Shows/Cloud+Cover/Episode-155-Offline-Storage-with-Donna-Malayeri和 http://azure.microsoft.com/documentation/videos/azure-mobile-services-offline-enabled-apps-with-donna-malayeri/ .
关于java - Azure 移动服务异步任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33622042/