【问题标题】:Best Approach using Volley Android to Insert SQLITE Database?使用 Volley Android 插入 SQLITE 数据库的最佳方法?
【发布时间】:2018-04-07 05:08:43
【问题描述】:

我在我的 android 应用程序中使用 Volley,但我遇到了一个问题,我只能将 volley 用于异步连接吗?

因为每个示例我有一个从 Web 服务到我的应用程序的 1800 条记录数据库,所以我开始 volley 并很好地检索,但我将这些记录插入到我的 SQLite 上,当我这样做时,我的应用程序冻结了,为什么?

我认为 volley 有异步方法来处理这个问题,但是当我在 volley 上循环并插入时它会冻结。我的对话停止了动画和一切。

在 volley 之前,我使用来自 android 的 Assyntask,从不冻结我的应用程序,我正在使用 httpost,但现在我改为 volley,我正面临这个问题,我将分享我的代码:

  public void volleyJsonObjectRequest(String url) {

        String  REQUEST_TAG = "com.androidtutorialpoint.volleyJsonObjectRequest";
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Sincronizando pedidos..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();

        // prepare the Request
        JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>()
                {
                    @Override
                    public void onResponse(JSONObject response) {
                        // display response

                        Log.d("Response", response.toString());

                        List<HashMap<String,String>> listObjectsServer = new ArrayList<>();

                        try {

                            MDAutomap controller;
                            controller = new MDAutomap(getActivity());


                            JSONArray jsonArrayPedidos = response.getJSONArray("pedidos");
                            if (jsonArrayPedidos != null && jsonArrayPedidos.length() > 0) {

                                HashMap<String, String> pedidos = new HashMap<String, String>();
                                for (int i = 0; i < jsonArrayPedidos.length(); i++) {

                                  JSONObject obj = jsonArrayPedidos.getJSONObject(i);

                                  pedidos.put("nomeusuario", obj.getString("nomeUsuario"));
                                  pedidos.put("id", obj.getString("id"));
                                  pedidos.put("nome", obj.getString("nome"));
                                  pedidos.put("eventoid", obj.getString("eventoid"));
                                  pedidos.put("descricao", obj.getString("descricao"));
                                  pedidos.put("valor", obj.getString("valor"));
                                  pedidos.put("veiculo", obj.getString("veiculo"));
                                  pedidos.put("transactioncode", obj.getString("transactioncode"));
                                  pedidos.put("referencecode", obj.getString("referencecode"));
                                  pedidos.put("status", obj.getString("status"));
                                  pedidos.put("flag", obj.getString("flag"));
                                  pedidos.put("usuario", obj.getString("usuario"));
                                  pedidos.put("created_at", obj.getString("created_at"));
                                  pedidos.put("updated_at", obj.getString("updated_at"));

                                    if (controller.checkPedido(pedidos.get("id"))) {

                                        controller.updatePedido(pedidos);

                                    }else {

                                        controller.inserirPedido(pedidos);

                                    }


                                }

                                if (pDialog != null && pDialog.isShowing()) {
                                    pDialog.dismiss();
                                }

                                //userMsg("Sincronizado com sucesso os pedidos.");

                            }else {

                                if (pDialog != null && pDialog.isShowing()) {
                                    pDialog.dismiss();
                                }


                                //userMsg("Não existe pedidos para sincronizar.");

                            }



                        } catch (JSONException e1) {
                            e1.printStackTrace();
                        }

                    }

                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                        if (pDialog != null && pDialog.isShowing()) {
                            pDialog.dismiss();
                        }
                        userMsg("Não foi possível fazer conexão, por favor tenta novamente.");
                    }
                }
        );

【问题讨论】:

  • 显示updatePedido和inserirPedido的代码

标签: android asynchronous android-sqlite android-volley


【解决方案1】:

是的,它会冻结,因为它正在从服务中获取大量数据并在主 UI 线程的 Db 中插入。所以我通过在凌空响应中执行异步任务解决了这个问题,它在我的情况下有效

private void hitApiForSyncDropdownsData(final String ApiType) {
    showDialog();
String jsonAsParamstr = makeJsonStr(ApiType);
JsonObjectRequest req = new JsonObjectRequest(wholeUrl, makeJsonFromStrJson(jsonAsParamstr),
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getString(Constant.Utils.responseCode).equals("1")) {
                        new ProcessJsonAsync(ApiType).execute(response, null, null);
 //processing response in Async as getting heavy reponse and inserting into DB
                    } else {
                        showShortToast(response.getString(Constant.Utils.responseMessage));
                        dismissDialog();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissDialog();
                }
            }

        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        VolleyLog.e("Error: ", error.getMessage());
        showmsgForVolleyIfConnProb(error, context);
    }
});
req = setretryPolicy(req);
AppController.getInstance().addToRequestQueue(req);
}

并且异步代码看起来像

private class ProcessJsonAsync extends AsyncTask<JSONObject, Void, Integer> {
        String ApiType;

        ProcessJsonAsync(String ApiType) {
            this.ApiType = ApiType;
        }

      protected Integer doInBackground(JSONObject... jsonObjects) {
        ArrayList<DataModel> dataModelArraylist = new ArrayList<>();

        Integer insertedResult = -1;
        try {
            JSONObject response = jsonObjects[0];
            if (response.getString(Constant.Utils.responseCode).equalsIgnoreCase("1")) {
                JSONArray jsonarray = response.getJSONArray(Constant.Utils.responseObject);
                for (int i = 0; i < jsonarray.length(); i++) {
                    JSONObject jsonObj = jsonarray.getJSONObject(i);
                    dataModelArraylist.add(new DataModel(jsonObj.getString("data1"), jsonObj.getString("data2"));
                }

                DataStrucTable dataStrucTable=new DataStructTable();
                insertedResult=dataStrucTable.insertArrayInDb(dataModelArraylist);
    //here it will insert thousands of entries in DB on background thread and will not hang your UI

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return insertedResult;
    }
      @Override
    protected void onPostExecute(Integer integer) {
        Toast.makeText(context, integer == -1 ? "Data couldn't insert in DB" :"Data successfully inserted", Toast.LENGTH_SHORT).show();
    }
    }

【讨论】:

  • 真的很好,我正在考虑这个问题,但我读了很多文章说 volley 是异步的,我认为这是我的问题之类的,但它是 volley 内部的一个很好的异步方法?
  • @Wavrik,如果解决了你的问题,请投我一票,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-08
  • 2010-11-13
相关资源
最近更新 更多