android – 如何在上传json数据时按百分比显示进度条状态?

前端之家收集整理的这篇文章主要介绍了android – 如何在上传json数据时按百分比显示进度条状态?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在上传字符串和照片.它的工作正常.现在我想显示进度条,同时上传数据百分比,但百分比显示很快达到100%,并花费更多时间上传,最后进入后执行方法.
  1. protected class upload_images extends AsyncTask<String,Integer,String> {
  2. ProgressDialog progressDialog;
  3. @Override
  4. protected void onPreExecute() {
  5. super.onPreExecute();
  6. // showDialog(progress_bar_type);
  7. progressDialog = new ProgressDialog(Accept_Report.this);
  8. progressDialog.setCancelable(false);
  9. // dialog.setCanceledOnTouchOutside(false);
  10. progressDialog.setIndeterminate(false);
  11. // progressDialog.setMax(100);
  12. progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  13. // progressDialog.setProgress(0);
  14. progressDialog.setMax(100);
  15. // progressDialog.setMessage("Loading ...");
  16. progressDialog.show();
  17. // ProgressBar progressBar = (ProgressBar)findViewById(R.id.progressBar2);
  18. }
  19. @Override
  20. protected String doInBackground(String... params) {
  21. URL url;
  22. HttpURLConnection connection = null;
  23. String http=Util.URL+"reports/media/create";
  24. try {
  25. url = new URL(http);
  26. connection = (HttpURLConnection) url.openConnection();
  27. connection.setDoInput(true);
  28. connection.setRequestMethod("POST");
  29. /* connection.setConnectTimeout(50000);
  30. connection.setReadTimeout(50000);*/
  31. connection.setRequestProperty("Content-Type","application/json");
  32. connection.setRequestProperty("Content-Language","en-US");
  33. String encoded = Base64.encodeToString(("app" + ":" + "sFif4au7wet8gpsT0boK1oM2Yud6M1").getBytes("UTF-8"),Base64.NO_WRAP);
  34. connection.setRequestProperty("Authorization","Basic " + encoded);
  35. connection.setUseCaches(false);
  36. connection.setDoOutput(true);
  37. connection.connect();
  38.  
  39. jsonArray = new JSONArray();
  40.  
  41. right = send_right.toString().replaceAll("\\[","").replaceAll("\\]","");
  42. if((right!=null)&&(right!="")) {
  43. JSONObject pnObj = new JSONObject();
  44. pnObj.put("comments",right_cm);
  45. pnObj.put("section",right_sec);
  46. pnObj.put("pictures",right);
  47. jsonArray.put(pnObj);
  48. }
  49.  
  50. // return totalSize;
  51.  
  52. JSONObject jsonParam = new JSONObject();
  53. jsonParam.put("media",jsonArray);
  54.  
  55. //Send request
  56.  
  57.  
  58. int count = 0;
  59. OutputStream wr = connection.getOutputStream();
  60. InputStream inputStream = null;
  61. byte[] payload = jsonParam.toString().getBytes("UTF-8");
  62. int totalSze = payload.length;
  63. Log.e("Total size ","" + totalSze);
  64. int bytesTransferred = 0;
  65. int chunkSize = (2*totalSze)/100;
  66. boolean last_loop = false;
  67. // publishProgress(0);
  68.  
  69. while (bytesTransferred < totalSze) {
  70.  
  71. Log.e("bytes transferred","" + bytesTransferred);
  72. int nextChunkSize = totalSze - bytesTransferred;
  73. Log.e("nextchunck",""+nextChunkSize);
  74.  
  75. //int writer_size = wr.toString().getBytes("UTF-8").length;
  76. Log.e("chunk size","" + chunkSize);
  77. if (nextChunkSize > chunkSize) {
  78. nextChunkSize = chunkSize;
  79. }
  80.  
  81.  
  82. wr.write(payload,bytesTransferred,nextChunkSize);
  83. bytesTransferred += nextChunkSize;
  84. Log.e("byte",""+wr.toString().getBytes("UTF-8").length);
  85.  
  86. Log.e("progress-transferred","" + bytesTransferred +" total "+totalSze);
  87.  
  88.  
  89. double cal = (( (double)bytesTransferred / (double) totalSze) * 100);
  90.  
  91. double rounded = (double) Math.round(cal * 100.0) / 100.0;
  92.  
  93. Log.e("progress",""+(int)rounded);
  94.  
  95. publishProgress((int)rounded);
  96.  
  97. wr.flush();
  98. wr.close();
  99.  
  100. }catch(Exception e){
  101. Log.d("Exception",e.toString());
  102. }
  103. }*/
  104. Log.e("While loop exit","");
  105. /* wr.flush ();
  106. wr.close();*/
  107.  
  108.  
  109. }catch (OutOfMemoryError e)
  110. {
  111. e.printStackTrace();
  112. }
  113.  
  114. //Get Response
  115. StringBuilder sb = new StringBuilder();
  116. HttpResultimage =connection.getResponseCode();
  117. Log.e("res",""+HttpResultimage);
  118.  
  119. if(HttpResultimage==204)
  120. {
  121. BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
  122. String line = null;
  123. while ((line = br.readLine()) != null) {
  124. sb.append(line + "\n");
  125. }
  126. br.close();
  127. System.out.println("" + sb.toString());
  128. }else{
  129. }
  130.  
  131.  
  132.  
  133. } catch (Exception e) {
  134. e.printStackTrace();
  135. return null;
  136. } finally {
  137. if(connection != null) {
  138. connection.disconnect();
  139. }
  140. }
  141. return null;
  142. }
  143. @Override
  144. protected void onProgressUpdate(Integer... values){
  145. super.onProgressUpdate(values);
  146. // Log.e("dfsf",""+values[0]);
  147. progressDialog.setProgress(values[0]);
  148. // progressDialog.setProgress(values[0]);
  149.  
  150. }
  151.  
  152. @Override
  153. protected void onPostExecute(String result) {
  154. if (HttpResultimage==204) {
  155. progressDialog.dismiss();
  156. }
  157. }
  158. }

解决方法

查看本教程 – http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/
  1. private class UploadFileToServer extends AsyncTask<Void,String> {
  2. @Override
  3. protected void onPreExecute() {
  4. // setting progress bar to zero
  5. progressBar.setProgress(0);
  6. super.onPreExecute();
  7. }
  8.  
  9. @Override
  10. protected void onProgressUpdate(Integer... progress) {
  11. // Making progress bar visible
  12. progressBar.setVisibility(View.VISIBLE);
  13.  
  14. // updating progress bar value
  15. progressBar.setProgress(progress[0]);
  16.  
  17. // updating percentage value
  18. txtPercentage.setText(String.valueOf(progress[0]) + "%");
  19. }
  20.  
  21. @Override
  22. protected String doInBackground(Void... params) {
  23. return uploadFile();
  24. }
  25.  
  26. @SuppressWarnings("deprecation")
  27. private String uploadFile() {
  28. String responseString = null;
  29.  
  30. HttpClient httpclient = new DefaultHttpClient();
  31. HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
  32.  
  33. try {
  34. AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
  35. new ProgressListener() {
  36.  
  37. @Override
  38. public void transferred(long num) {
  39. publishProgress((int) ((num / (float) totalSize) * 100));
  40. }
  41. });
  42.  
  43. File sourceFile = new File(filePath);
  44.  
  45. // Adding file data to http body
  46. entity.addPart("image",new FileBody(sourceFile));
  47.  
  48. // Extra parameters if you want to pass to server
  49. entity.addPart("website",new StringBody("www.androidhive.info"));
  50. entity.addPart("email",new StringBody("abc@gmail.com"));
  51.  
  52. totalSize = entity.getContentLength();
  53. httppost.setEntity(entity);
  54.  
  55. // Making server call
  56. HttpResponse response = httpclient.execute(httppost);
  57. HttpEntity r_entity = response.getEntity();
  58.  
  59. int statusCode = response.getStatusLine().getStatusCode();
  60. if (statusCode == 200) {
  61. // Server response
  62. responseString = EntityUtils.toString(r_entity);
  63. } else {
  64. responseString = "Error occurred! Http Status Code: "
  65. + statusCode;
  66. }
  67.  
  68. } catch (ClientProtocolException e) {
  69. responseString = e.toString();
  70. } catch (IOException e) {
  71. responseString = e.toString();
  72. }
  73.  
  74. return responseString;
  75.  
  76. }
  77.  
  78. @Override
  79. protected void onPostExecute(String result) {
  80. Log.e(TAG,"Response from server: " + result);
  81.  
  82. // showing the server response in an alert dialog
  83. showAlert(result);
  84.  
  85. super.onPostExecute(result);
  86. }
  87.  
  88. }

猜你在找的Android相关文章