ProgressBar始终保持为0%但日志语句显示增加的百分比

时间:2016-01-19 06:43:06

标签: android android-asynctask

我正在向服务器发布一些json数据,但是我想检查所发送数据的进度,所以我添加了一个进度条来指示我发送的数据百分比,但进度条保持在0%,所以我放了一个日志语句,我可以看到进度条递增5。

这是我试过的代码。

Asynctask类

 private class SyncPodData extends AsyncTask<Integer,Integer,Void>{
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog = new ProgressDialog(Add_Pod.this);
        mProgressDialog.setMessage("POD details syncing.. please wait !!!");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgress(0);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(true);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setOnDismissListener(new 
        DialogInterface.OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface dialog) {
                dialog.dismiss();
                mProgressDialog.cancel();
                new SyncPodData().cancel(true);
            }
        });
        mProgressDialog.show();
    }

    @Override
    protected Void doInBackground(Integer... params) {
        int count = 0;
        try {
            TelephonyManager telephonyManager = (TelephonyManager) 
            getSystemService(Context.TELEPHONY_SERVICE);
            String IMEI_No = telephonyManager.getDeviceId();
            if (IMEI_No == null) {
                Toast.makeText(getApplicationContext(),
                        "Problem IMEI", Toast.LENGTH_LONG).show();
            } else {
                if (isInternetPresent) {
                    cursor = quickSnapHelper.getPodSyncDetails(oldSYnc);
                    if (cursor.getCount() == 0) {
                    }
                    else{
                        try{
                            HTTPCalls httpCalls = new HTTPCalls();
                            JSONObject jsonObj = httpCalls.jo(url, 
                            imeiNumber, verificationCode, appName);
                            String token = jsonObj.getString("Token");
                            String tUrl = jsonObj.getString("Url");
                            tUrl = tUrl.toString().concat("postImage");
                            JSONArray jArray1 = new JSONArray();
                            while (cursor.moveToNext()) {
                                JSONObject json = new JSONObject();
                                json.put("CategoryName","POD");
                                json.put("SubCategory", passedType);
                                json.put("Image1", image1);
                                json.put("Image2", image2);
                                json.put("Image3", image3);
                                json.put("Image4", image4);
                                json.put("DODC", doe);
                                jArray1.put(json);
                            }
                            int jsonarrayLength = jArray1.length();
                            HttpParams httpParams = new BasicHttpParams();
                            HttpClient client = new  
                            DefaultHttpClient(httpParams);
                            HttpPost request = new HttpPost(tUrl);
                            request.setHeader("Authorization", basicAuth);
                            request.setHeader(HTTP.CONTENT_TYPE, 
                            "application/json");

                            HttpResponse response = client.execute(request);
                            Log.d("Http Response:  ", response.toString());
                            statusLine = response.getStatusLine();
                            code = statusLine.getStatusCode();
                            HttpEntity entity = response.getEntity();
                            if (entity != null) {
                                InputStream instream = entity.getContent();

                               // publish progress //
                                while(count != 100){
                                    publishProgress(count);
                                    count += 5;
                                }

                                BufferedReader reader = new 
                            BufferedReader(new InputStreamReader(instream));
                                String line1;
                                StringBuilder sb = new StringBuilder();
                                while ((line1 = reader.readLine()) != null)  
                                {
                                    sb.append(line1);
                                }
                                String result = sb.toString();
                                result = result.trim();
                                instream.close();
                                Log.d("Result:", result);
                                String responseCode = String.valueOf(code);
                                Log.d("Code:", responseCode);
                                JSONArray jsonArray = new JSONArray(result);
                                for(int i = 0; i < jsonArray.length(); i++){
                                    JSONObject jsonObject = 
                                    jsonArray.getJSONObject(i);
                                    resultTransId =  
                                    jsonObject.getString("TransactionId");
                                }
                                Log.d("Transaction Id", resultTransId);
                                if (code >= 400) {
                                    Add_Pod.this.runOnUiThread(new  
                                        Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(getBaseContext(), 
                                           "Data sync failed!!!"+"\n"+
                                            Toast.LENGTH_LONG).show();
                                        }
                                    });
                                }
                                else if (code == 200 && 
                                transId.equals(resultTransId)) {
                                    updaterow();
                                    Add_Pod.this.runOnUiThread(new 
                                      Runnable() {

                                        @Override
                                        public void run() {
                                            Toast.makeText(getBaseContext(), 
                                            "Data sync completed",     
                                            Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                } 
                            }
                        }
                        catch (UnknownHostException ex){
                            ex.printStackTrace();
                            Add_Pod.this.runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    Toast.makeText(getBaseContext(), "Please    
              check your internet connection!!!", Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                        catch (Exception e){
                            e.printStackTrace();
                            Add_Pod.this.runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    Toast.makeText(getBaseContext(), "Data  
                                            sync failed!!!"+"\n"+
                                            Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                    }
                } else {
                    showAlertDialog(Add_Pod.this, "No Internet Connection",  
                    "You don't have internet connection.",
                            false);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        Log.d("Progress Value", "" + values[0]);
        mProgressDialog.setProgress(values[0]);
}

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        if(mProgressDialog.isShowing()){
            mProgressDialog.dismiss();
        }
    }
}

请提出一些建议。

LogCat:

D /进度值:5 D /进度值:10 D /进度值:15 D /进度值:20 D /进度值:25 D /进度值:30 D /进度值:35 D /进度值:40 D /进度值:45 D /进度值:50 D /进度值:55 D /进度值:60 D /进度值:65 D /进度值:70 D /进度值:75 D /进度值:80 D /进度值:85 D /进度值:90 D /进度值:95

1 个答案:

答案 0 :(得分:0)

在你的AsyncClass中声明两个int变量,名为length和calculatedVal.After声明HttpEntity变量,在if块中你提供的entity!= null条件, 将长度初始化为:

 length = entity.getContentLength();

在onProgressUpdate()内部,初始化calculatedVal并将进度值设置为:

 calculatedVal = (int) (((double) values[0] / length) * 100);
 mProgressDialog.setProgress(calculatedVal);

您需要在进度条中显示已下载了多少文件以及剩余多少文件。为此,您需要考虑最高规定的计算值。希望它会帮助您