没有观察地从房间中选择数据

问题描述 投票:0回答:1

我需要从一个表中选择数据,对其进行操作,然后将其插入另一个表中。仅在当天第一次打开应用程序时才会发生这种情况,并且不会在UI中使用。我不想使用LiveData,因为不需要观察它,但是当我研究如何做时,大多数人说我应该使用LiveData。我尝试使用AsyncTask,但收到错误消息“由于可能潜在的原因,无法访问主线程上的数据库。”。这是我的AsyncTask的代码

 public class getAllClothesArrayAsyncTask extends AsyncTask<ArrayList<ClothingItem>, Void, ArrayList<ClothingItem>[]> {

        private ClothingDao mAsyncDao;
        getAllClothesArrayAsyncTask(ClothingDao dao) { mAsyncDao = dao;}


        @Override
        protected ArrayList<ClothingItem>[] doInBackground(ArrayList<ClothingItem>... arrayLists) {

            List<ClothingItem> clothingList  = mAsyncDao.getAllClothesArray();
            ArrayList<ClothingItem> arrayList = new ArrayList<>(clothingList);
            return arrayLists;
        }
    }

这就是我在活动中这样称呼它的方式

        mClothingViewModel = new ViewModelProvider(this).get(ClothingViewModel.class);
        clothingItemArray = mClothingViewModel.getClothesArray();

在这种情况下的最佳做法是什么?

java android-studio android-asynctask android-room android-livedata
1个回答
0
投票

简要摘要

  1. Room实际上不允许在主线程上执行任何操作(查询|插入|更新|删除)。您可以在RoomDatabaseBuilder上关闭此控件,但最好不要这样做。
  2. 如果您不关心UI,则至少可以将ROOM式代码(Runnable)放到Thread,Executor,AsyncTask(但已于去年弃用)之一中……我已经举了一些例子下面
  3. 我认为对数据库的这一一次性操作中的最佳实践是协程(对于那些在项目中使用Kotlin的人)和RxJava(对于那些使用Java的人,可能将Single |也许作为返回类型)。它们提供了更多的可能性,但是您应该花费时间来理解这些机制。
  4. 要观察来自Room的数据流,请使用LiveData,Coroutines Flow,RxJava(Flowable)。

使用启用了lambda的线程切换的几个示例(如果您出于某种目的不想学习更多高级知识)]:

  • 只是一个线程

    new Thread(() -> { List<ClothingItem> clothingList = mAsyncDao.getAllClothesArray(); // ... next operations });

  • 执行人

  • Executors.newSingleThreadExecutor().submit(() -> { List<ClothingItem> clothingList = mAsyncDao.getAllClothesArray(); // ... next operations });

  • AsyncTask

  • AsyncTask.execute(() -> { List<ClothingItem> clothingList = mAsyncDao.getAllClothesArray(); // ... next operations });

    如果您使用存储库模式,则可以将所有线程切换放在此处

Another useful link了解AsyncTask弃用后的生活

© www.soinside.com 2019 - 2024. All rights reserved.