【发布时间】:2020-05-10 23:52:18
【问题描述】:
我需要从表中选择数据,对其进行操作,然后将其插入到另一个表中。这只发生在当天第一次打开应用程序并且不会在 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