我需要从一个表中选择数据,对其进行操作,然后将其插入另一个表中。仅在当天第一次打开应用程序时才会发生这种情况,并且不会在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();
在这种情况下的最佳做法是什么?
简要摘要:
使用启用了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弃用后的生活