如何在Room的异步后台任务中写入和读取数据?

2022-03-09 00:00:00 android android-room java android-volley

我想在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

相关文章