How can I write and read data in async background task in Room?(如何在Room的异步后台任务中写入和读取数据?)
问题描述
我想在volley库的帮助下将Web上的JSON内容保存到Room中。
allowMainThreadQueries()
我在Room builder部分添加了这个,但是当执行data insert和getall方法时,屏幕冻结。就不能手术了。我如何在后台执行此操作?
关于LiveData,我找不到一个足够简单的解释,除此之外,我对你们将要举的例子很好奇。请展开此问题
public void getFoodRequest() {
Log.d("TAG_JSON_FOOD_DB", "--------------------------------");
foodList.clear();
@SuppressLint("SetJavaScriptEnabled") JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
Constant.FOOD_LIST_JSON, null,
response -> {
long start = System.currentTimeMillis();
try {
JSONArray jsonArray = response.getJSONArray("MyData");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
FoodArray foodArray = new FoodArray();
List<FoodUnitsData> foodUnitList = new ArrayList<>();
FoodsData foodsData = new FoodsData();
foodsData.setFoodId(object.getString("food_id"));
foodsData.setFoodName(object.getString("food_name"));
foodsData.setFoodImage(object.getString("food_image"));
foodsData.setFoodUrl(object.getString("food_url"));
foodsData.setFoodKcal(object.getString("food_kcal"));
foodsData.setFoodDescription(object.getString("food_description"));
foodsData.setCarbPercent(object.getString("carb_percent"));
foodsData.setProteinPercent(object.getString("protein_percent"));
foodsData.setFatPercent(object.getString("fat_percent"));
JSONArray jsonUnitsArray = object.getJSONArray("units");
for (int k = 0; k < jsonUnitsArray.length(); k++) {
JSONObject unitobject = jsonUnitsArray.getJSONObject(k);
FoodUnitsData foodUnitData = new FoodUnitsData();
foodUnitData.setUnit(unitobject.getString("unit"));
foodUnitData.setAmount(unitobject.getString("amount"));
foodUnitData.setCalory(unitobject.getString("calory"));
foodUnitData.setCalcium(unitobject.getString("calcium"));
foodUnitData.setCarbohydrt(unitobject.getString("carbohydrt"));
foodUnitData.setCholestrl(unitobject.getString("cholestrl"));
foodUnitData.setFiberTd(unitobject.getString("fiber_td"));
foodUnitData.setIron(unitobject.getString("iron"));
foodUnitData.setLipidTot(unitobject.getString("lipid_tot"));
foodUnitData.setPotassium(unitobject.getString("potassium"));
foodUnitData.setProtein(unitobject.getString("protein"));
foodUnitData.setVitAIu(unitobject.getString("vit_a_iu"));
foodUnitData.setVitC(unitobject.getString("vit_c"));
foodUnitList.add(foodUnitData);
}
foodArray.setFoods(foodsData);
foodArray.setFoodUnits(foodUnitList);
appDatabase.daoAccess().insertAll(foodArray); // insert
}
foodsArray = appDatabase.daoAccess().getAll(); // get all data
for (int i = 0; i < foodsArray.size(); i++) {
Log.d("TAG_JSON_FOOD_DB", "---------: " + "" + foodsArray.get(i).getFoods().getFoodName());
}
long finish = System.currentTimeMillis();
Log.d("TAG_JSON_FOOD_DB", " " + (finish - start));
Log.d("TAG_JSON_FOOD_DB", " " + "******************
");
} catch (JSONException e) {
e.printStackTrace();
Log.d("TAG_JSON_FOOD", "e:" + e);
}
}, error -> {
Log.d("TAG_JSON_FOOD", error.toString());
});
jsonObjectRequest.setShouldCache(false);
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue request_queue = Volley.newRequestQueue(context);
request_queue .add(jsonObjectRequest);
}
推荐答案
需要更多信息才能回答您的问题。例如,";daoAccess().getAll()";的返回类型是什么?它是实时数据吗?(我假设是这样)。
此代码来自片段/活动还是视图模型?(我假定这是ViewModel)
不要将LiveData视为您需要的值,而应将其视为一个标志,该标志将告诉您该值已准备就绪,可以读取。
daoAccess().getAll()
将返回LiveData<SomeObjectProbablyAList>
由于";getall";方法在您的viewModel中,您将把返回值存储在LiveData变量中,假设:
val returnValue: `LiveData<SomeObjectProbablyAList> = MutableLiveData<SomeObjectProbablyAList>
您需要在viewModelScope内运行代码 查看:https://developer.android.com/topic/libraries/architecture/coroutines如何在后台执行此操作?
从您的片段/活动中,您将观察到viewModel处的rereturn Value。
在您的ViewModel中完成请求之后,您将更新rereturn Value。由于您的frag/活动正在观察rereturn Value,因此一旦它更新,您就可以运行您的片段/viewModel中的任何代码。
您可以在此处找到有关liveData的更多信息: https://developer.android.com/topic/libraries/architecture/livedata
这篇关于如何在Room的异步后台任务中写入和读取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在Room的异步后台任务中写入和读取数据?
基础教程推荐
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01