我在使用asynctask在我的云数据库中查询时遇到了一些麻烦。
由于查询的响应延迟,我无法正确获得结果。获得NULL。
main activity.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
}
box DAO.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;
}
在asynctask完成之前,我总是变为NULL。但我需要在同一时间得到结果。我怎么解决这个问题?我搜索过asynctask,但我没有找到这样的东西。
谢谢。
你的代码是正确的,它工作正常。但是,如果要在显示的UI的同一时间显示结果,则无法使用asynctask轻松解决。
根据我的经验,有两种方法可以帮助解决这个问题。
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/。