【问题标题】:Azure mobile service asynctaskAzure 移动服务异步任务
【发布时间】:2015-11-10 02:49:44
【问题描述】:

我在使用异步任务查询我的云数据库时遇到了一些麻烦。

由于查询的响应延迟,我无法正确获得结果。获取 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,但没有找到类似的东西。

谢谢。

【问题讨论】:

    标签: java azure azure-mobile-services


    【解决方案1】:

    您的代码是正确的,并且运行良好。但是,如果你想让结果在 UI 显示的同时显示,使用 asynctask 不是很容易解决的。

    根据我的经验,有两种方法可以帮助解决这个问题。

    1. 去掉asynctask代码,使用sync方式获取数据,但会导致UI挂起,不推荐。

    2. 使用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-Malayerihttp://azure.microsoft.com/documentation/videos/azure-mobile-services-offline-enabled-apps-with-donna-malayeri/

    【讨论】:

    • 您好,感谢您的支持。要实现第一个答案,我需要将我的 azureget 方法更改为同步方法吗?我已经编辑了我的问题。
    • 没关系,我用的是第二个。更可靠、更简单。
    • @Warkold 很好。有任何问题,请随时告诉我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 2013-11-14
    相关资源
    最近更新 更多