Volley ProgressDialog在获取大量数据时卡住/冻结

时间:2015-01-16 06:15:50

标签: android android-volley

这是我的代码:

private void downloadSupplyTownData(final int townId2) {

    /*******************
     * Using Volley
     *******************/
    // Post params to be sent to the server
    HashMap<String, Object> params = new HashMap<String, Object>();
    params.put("ID",townId2);
   CustomDialogClass.showProgressDialog(context,true); 


    JsonObjectRequest req = new JsonObjectRequest(Consts.baseUrl+Consts.townSupplyUrl, new JSONObject(params),
           new Response.Listener<JSONObject>() {
               @Override
               public void onResponse(JSONObject response) {
                   try {
                       totalConsumerRecords =   Integer.parseInt(response.getString("TotalConsumerRecords").trim());
                       if(totalConsumerRecords>0)
                       {                               
                           /**For -----**/
                           JSONArray dtrArray   =   response.getJSONArray("xxx");
                           for(int i=0;i<dtrArray.length();i++)
                           {
                               JSONObject   dtrObj  =   dtrArray.getJSONObject(i);
                               supplyId1        =   Integer.parseInt(dtrObj.getString("SI"));
                               dtrId            =   Integer.parseInt(dtrObj.getString("DI"));
                               dtrImgUrl        =   dtrObj.getString("DIMG");
                               dtrCode          =   dtrObj.getString("DC");
                               assetPCode       =   dtrObj.getString("APC");
                               meterSN          =   dtrObj.getString("MSN");
                               System.out.println(dtrId);
                               db.addDtrInfo(new DTRBeanClass(dtrId,supplyId1,dtrCode,dtrImgUrl,assetPCode,meterSN));
                           }

                           /**For ----**/
                           JSONArray poleArray  =   response.getJSONArray("Pole");
                           for(int i=0;i<poleArray.length();i++)
                           {
                               JSONObject   poleObj =   poleArray.getJSONObject(i);
                               poleId           =   Integer.parseInt(poleObj.getString("PI"));
                               dtrId1           =   Integer.parseInt(poleObj.getString("DI"));
                               consumerCount    =   Integer.parseInt(poleObj.getString("ACA"));
                               poleImgUrl       =   poleObj.getString("PIMG");
                               poleCode         =   poleObj.getString("PC");
                               surveyerRemarks  =   poleObj.getString("RMS");
                               System.out.println(poleId);
                               db.addPoleInfo(new PoleBeanClass(poleId,dtrId1,poleCode,poleImgUrl,consumerCount,surveyerRemarks));
                           }

                           /**For ----**/
                           JSONArray consumerArray  =   response.getJSONArray("Supply");
                           for(int i=0;i<consumerArray.length();i++)
                           {
                               JSONObject   supplyObj   =   consumerArray.getJSONObject(i);
                               supplyId     =   Integer.parseInt(supplyObj.getString("SI"));
                               supplyTownId =   Integer.parseInt(supplyObj.getString("TI"));
                               supplyName   =   supplyObj.getString("SN");
                               System.out.println(supplyId);
                               db.addSupplierInfo(new SupplierChainBeanClass(supplyId,supplyTownId,supplyName));
                           }

                           CustomDialogClass.showProgressDialog(context,false);
                       }
                       else
                       {
                           CustomDialogClass.showProgressDialog(context,false);
                       }

                    } catch (JSONException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }                                                          
               }
           }, new Response.ErrorListener() {
               @Override
               public void onErrorResponse(VolleyError error) {
                   NetworkResponse networkResponse = error.networkResponse;
                   VolleyLog.e("Error: ", error.getMessage());
                   Log.d("Eroor", ""+networkResponse);
                   CustomDialogClass.showProgressDialog(context,false);
               }
           });

    // add the request object to the queue to be executed
    NameApplication.getInstance().addToRequestQueue(req);
}

此处按CustomDialogClass.showProgressDialog(context,true);

显示和隐藏ProgressDialog

进度对话框先旋转2-3秒然后卡住。请帮我解决这个问题。

修改

/ **      *显示对话框      * * /     @覆盖     protected Dialog onCreateDialog(int id){         switch(id){         case progress_bar_type://我们将其设置为0             pDialog = new ProgressDialog(this);             pDialog.setMessage(“正在下载文件。请稍候...”);             pDialog.setIndeterminate(假);             pDialog.setMax(100);             pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);             pDialog.setCancelable(真);             pDialog.show();             返回pDialog;         默认:             return null;         }     }

/**
 * Background Async Task to download file
 * */
class DownloadFileFromURL extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread
     * Show Progress Bar Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(progress_bar_type);
    }

    /**
     * Downloading file in background thread
     * */
    @Override
    protected String doInBackground(String... f_url) {
        downloadSupplyTownData(townId);

        return null;
    }

    /**
     * Updating progress bar
     * */
    protected void onProgressUpdate(String... progress) {
        // setting progress percentage
        pDialog.setProgress(Integer.parseInt(progress[0]));
   }

    /**
     * After completing background task
     * Dismiss the progress dialog
     * **/
    @Override
    protected void onPostExecute(String file_url) {            
        dismissDialog(progress_bar_type);

    }

}

从视图中调用AsynchTask new DownloadFileFromURL().execute();

1 个答案:

答案 0 :(得分:7)

  

进度对话框先旋转2-3秒然后卡住。

因为解析了json响应和downloadConsumerData方法从主UI线程发出api请求。

在网络请求完成时,在主要UI线程上调用的Volley onResponse方法作为回调方法。

要在onResponse方法中解析请求响应,请使用AsyncTask类,并在ProgressDialog方法中调用onPostExecute解除方法,该方法将在Volley请求时关闭ProgressDialog,解析json数据和downloadConsumerData方法作业在后台线程

中完成

onResponse方法启动AsyncTask:

  @Override
      public void onResponse(JSONObject response) {
       new DownloadFileFromURL().execute(response);
  }

doInBackground处理JSON数据中:

  @Override
    protected String doInBackground(String... f_url) {
         totalConsumerRecords = Integer.parseInt(response.getString
                           ("TotalConsumerRecords").trim());
        // add all code here from onResponse
        downloadSupplyTownData(townId);

        return null;
    }