【问题标题】:Return value from thread (runnable)从线程返回值(可运行)
【发布时间】:2018-04-17 19:22:31
【问题描述】:

我正在使用 Room 来持久化数据,新的 AAC 用于持久化数据,我正在开发一个应用程序,Google's github repository 中提供的 Todo 应用程序作为我们的蓝图。
我一直在尝试获取在实体上执行的事务返回的值。我使用了一个全局变量mCategories 来检索和存储返回的数据,但我一直在返回一个空对象。

这是我的代码:

 public interface LoadDataListener<T>
{
    void onReadTransactionCompleted(T arg);
}

private void readTransaction(final LoadDataListener<List<Category>> loadDataListener, final boolean onlyClassic)
{
    Runnable readRunnable = new Runnable() {
        @Override
        public void run() {
            List<Category> categories;
            if (!onlyClassic)
                categories = mCategoryDAO.loadAllSellingCategories();
            else
                categories = mCategoryDAO.loadAllClassicCategories();

            LOGD(TAG, "Category size: "+ categories.size());
            // The log above reads a value > 0
            loadDataListener.onReadTransactionCompleted(categories);
        }
    };

    mAppExecutors.diskIO().execute(readRunnable);
}

private List<Category> getSanitizedAndPersistedCategories(boolean onlyClassic) {
    readTransaction(new LoadDataListener<List<Category>>() {
        @Override
        public void onReadTransactionCompleted(List<Category> arg) {
            mCategories = arg;
            LOGD(TAG, "sanitizeCategoriesList size before: " + mCategories);
            // The log above reads a value > 0

        }
    }, onlyClassic);

    LOGD(TAG, "sanitizeCategoriesList size after: " + mCategories);
    // The log above reads null
    return sanitizeCategoriesList(mCategories);
}

我在这里错过了什么??

【问题讨论】:

    标签: android dao runnable android-room


    【解决方案1】:

    那是因为您在这里有 2 个线程
    当您调用readTransaction() 然后调用mAppExecutors.diskIO().execute(readRunnable) 时,方法readTransaction() 立即返回并调用LOGD(TAG, "sanitizeCategoriesList size after: " + mCategories);,正如预期的那样打印null。同时,在第二个线程上异步执行run(),在末尾调用onReadTransactionCompleted(),最后设置mCategories的值。

    所以你只能在调用onReadTransactionCompleted() 之后依赖mCategories

    如果您将mCategories 用于UI 相关的东西,您可能需要考虑使用AsyncTask 并将您的代码从run() 移动到doInBackground() 并将代码从onReadTransactionCompleted() 移动到onPostExecute()

    【讨论】:

      猜你喜欢
      • 2013-11-06
      • 2012-02-27
      • 1970-01-01
      • 1970-01-01
      • 2011-01-19
      • 2021-10-24
      相关资源
      最近更新 更多