问题
I got some trouble using the asynctask to query in my cloud database.
Due the response delay to query I cant get the result correctly. Getting 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;
}
I am getting always NULL until the asynctask has finished. but I need the result in the same time. How can I solve that? I've searched about asynctask but I didnt find anything like this.
Thank you.
回答1:
Your code is correct, and it works fine. However, if you want to get the result to show in the same time of UI displayed, you can not solve it easily by using the asynctask.
Per my experience, there are two ways can help solve that.
Remove the asynctask code and use the sync method to get data, but it will cause UI hang so that it not be recommended.
Use
MobileServiceSyncTable
to enable offline sync to solve it.
There is a sample doc https://azure.microsoft.com/en-us/documentation/articles/mobile-services-android-get-started-offline-data/ to help adding offline data sync into your app.
You alse can watch some vedio to learn it, please move to http://channel9.msdn.com/Shows/Cloud+Cover/Episode-155-Offline-Storage-with-Donna-Malayeri and http://azure.microsoft.com/documentation/videos/azure-mobile-services-offline-enabled-apps-with-donna-malayeri/.
来源:https://stackoverflow.com/questions/33622042/azure-mobile-service-asynctask