本文介紹了如何在Room的異步后臺(tái)任務(wù)中寫入和讀取數(shù)據(jù)?的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我想在volley庫的幫助下將Web上的JSON內(nèi)容保存到Room中。
allowMainThreadQueries()
我在Room builder部分添加了這個(gè),但是當(dāng)執(zhí)行data insert和getall方法時(shí),屏幕凍結(jié)。就不能手術(shù)了。我如何在后臺(tái)執(zhí)行此操作?
關(guān)于LiveData,我找不到一個(gè)足夠簡(jiǎn)單的解釋,除此之外,我對(duì)你們將要舉的例子很好奇。請(qǐng)展開此問題
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()";的返回類型是什么?它是實(shí)時(shí)數(shù)據(jù)嗎?(我假設(shè)是這樣)。
此代碼來自片段/活動(dòng)還是視圖模型?(我假定這是ViewModel)
不要將LiveData視為您需要的值,而應(yīng)將其視為一個(gè)標(biāo)志,該標(biāo)志將告訴您該值已準(zhǔn)備就緒,可以讀取。
daoAccess().getAll()
將返回LiveData<SomeObjectProbablyAList>
由于";getall";方法在您的viewModel中,您將把返回值存儲(chǔ)在LiveData變量中,假設(shè):
val returnValue: `LiveData<SomeObjectProbablyAList> = MutableLiveData<SomeObjectProbablyAList>
如何在后臺(tái)執(zhí)行此操作?
您需要在viewModelScope內(nèi)運(yùn)行代碼
查看:https://developer.android.com/topic/libraries/architecture/coroutines
從您的片段/活動(dòng)中,您將觀察到viewModel處的rereturn Value。
在您的ViewModel中完成請(qǐng)求之后,您將更新rereturn Value。由于您的frag/活動(dòng)正在觀察rereturn Value,因此一旦它更新,您就可以運(yùn)行您的片段/viewModel中的任何代碼。
您可以在此處找到有關(guān)liveData的更多信息:
https://developer.android.com/topic/libraries/architecture/livedata
這篇關(guān)于如何在Room的異步后臺(tái)任務(wù)中寫入和讀取數(shù)據(jù)?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,