使用Volley Android插入SQLITE数据库的最佳方法?

时间:2018-04-07 05:08:44

标签: android asynchronous android-sqlite android-volley

我在我的Android应用程序中使用Volley但是我遇到了问题,我只能使用凌空来进行异步连接?

因为每个例子我有一个从Web服务到我的应用程序的1800记录数据库我开始我的排球并且检索正常但是我将这些记录插入我的SQLite并且当我这样做时我的应用程序freezy为什么?

我认为凌空有异步方法来处理这个问题,但是当我在一个齐射和插入时循环时它会自由。我的对话会停止动画和所有内容。

在凌空之前,我使用了Android的Assyntask并且永远不会冻结我的应用程序而且我正在使用httpost但现在我改为截击并且我正面临这个问题我会分享我的代码:

  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.");
                    }
                }
        );

1 个答案:

答案 0 :(得分:0)

是的,它会冻结,因为它从服务获取大量数据并在主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();
    }
    }