2016-05-26 36 views
6

Sto caricando string e photo.and funziona bene. Ora voglio mostrare la barra di avanzamento durante il caricamento dei dati con percentuale, ma la percentuale mostra molto rapidamente a 100% e impiega un po 'più di tempo per caricare e infine giungere al metodo di esecuzione post.Come visualizzare lo stato della barra di avanzamento in base alla percentuale durante il caricamento dei dati JSON?

protected class upload_images extends AsyncTask<String, Integer, String> { 
     ProgressDialog progressDialog; 
      @Override 
      protected void onPreExecute() { 
       super.onPreExecute(); 
       // showDialog(progress_bar_type); 
       progressDialog = new ProgressDialog(Accept_Report.this); 
       progressDialog.setCancelable(false); 
       // dialog.setCanceledOnTouchOutside(false); 
       progressDialog.setIndeterminate(false); 
       // progressDialog.setMax(100); 
       progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
       // progressDialog.setProgress(0); 
       progressDialog.setMax(100); 
       // progressDialog.setMessage("Loading ..."); 
       progressDialog.show(); 
      // ProgressBar progressBar = (ProgressBar)findViewById(R.id.progressBar2); 
      } 
      @Override 
      protected String doInBackground(String... params) { 
       URL url; 
       HttpURLConnection connection = null; 
       String http=Util.URL+"reports/media/create"; 
       try { 
        url = new URL(http); 
        connection = (HttpURLConnection) url.openConnection(); 
        connection.setDoInput(true); 
        connection.setRequestMethod("POST"); 
        /* connection.setConnectTimeout(50000); 
        connection.setReadTimeout(50000);*/ 
        connection.setRequestProperty("Content-Type", "application/json"); 
        connection.setRequestProperty("Content-Language", "en-US"); 
        String encoded = Base64.encodeToString(("app" + ":" + "sFif4au7wet8gpsT0boK1oM2Yud6M1").getBytes("UTF-8"), Base64.NO_WRAP); 
        connection.setRequestProperty("Authorization", "Basic " + encoded); 
        connection.setUseCaches(false); 
        connection.setDoOutput(true); 
        connection.connect(); 

        jsonArray = new JSONArray(); 

        right = send_right.toString().replaceAll("\\[", "").replaceAll("\\]", ""); 
        if((right!=null)&&(right!="")) { 
         JSONObject pnObj = new JSONObject(); 
         pnObj.put("comments", right_cm); 
         pnObj.put("section", right_sec); 
         pnObj.put("pictures", right); 
         jsonArray.put(pnObj); 
        }  

         // return totalSize; 

        JSONObject jsonParam = new JSONObject(); 
        jsonParam.put("media", jsonArray); 

        //Send request 


         int count = 0; 
         OutputStream wr = connection.getOutputStream(); 
         InputStream inputStream = null; 
         byte[] payload = jsonParam.toString().getBytes("UTF-8"); 
         int totalSze = payload.length; 
         Log.e("Total size ", "" + totalSze); 
         int bytesTransferred = 0; 
         int chunkSize = (2*totalSze)/100; 
         boolean last_loop = false; 
         // publishProgress(0); 

         while (bytesTransferred < totalSze) { 

          Log.e("bytes transferred", "" + bytesTransferred); 
          int nextChunkSize = totalSze - bytesTransferred; 
          Log.e("nextchunck",""+nextChunkSize); 

          //int writer_size = wr.toString().getBytes("UTF-8").length; 
          Log.e("chunk size", "" + chunkSize); 
          if (nextChunkSize > chunkSize) { 
           nextChunkSize = chunkSize; 
          } 


          wr.write(payload, bytesTransferred, nextChunkSize); 
          bytesTransferred += nextChunkSize; 
          Log.e("byte",""+wr.toString().getBytes("UTF-8").length); 

          Log.e("progress-transferred", "" + bytesTransferred +" total "+totalSze); 


          double cal = (((double)bytesTransferred/(double) totalSze) * 100); 

          double rounded = (double) Math.round(cal * 100.0)/100.0; 

          Log.e("progress",""+(int)rounded); 

          publishProgress((int)rounded); 

         wr.flush(); 
         wr.close(); 

          }catch(Exception e){ 
           Log.d("Exception", e.toString()); 
          } 
         }*/ 
         Log.e("While loop exit", ""); 
         /* wr.flush(); 
         wr.close();*/ 


        }catch (OutOfMemoryError e) 
        { 
         e.printStackTrace(); 
        } 

        //Get Response 
        StringBuilder sb = new StringBuilder(); 
        HttpResultimage =connection.getResponseCode(); 
        Log.e("res",""+HttpResultimage); 

        if(HttpResultimage==204) 
        { 
         BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8")); 
         String line = null; 
         while ((line = br.readLine()) != null) { 
          sb.append(line + "\n"); 
         } 
         br.close(); 
         System.out.println("" + sb.toString()); 
        }else{ 
        } 



       } catch (Exception e) { 
        e.printStackTrace(); 
        return null; 
       } finally { 
        if(connection != null) { 
         connection.disconnect(); 
        } 
       } 
       return null; 
      } 
      @Override 
      protected void onProgressUpdate(Integer... values){ 
       super.onProgressUpdate(values); 
       // Log.e("dfsf",""+values[0]); 
       progressDialog.setProgress(values[0]); 
      // progressDialog.setProgress(values[0]); 

      } 

      @Override 
      protected void onPostExecute(String result) { 
       if (HttpResultimage==204) { 
        progressDialog.dismiss(); 
       } 
      } 
     } 
+0

1. Do 80% durante il caricamento e il 20% quando la risposta Get Back, 2. Non vicino flusso di output durante la scrittura ad esso. basta sciacquarlo. e post aumento – Qamar

+0

ero chiuso flusso di output nella mia codifica e ho bisogno di mostrare percentuale di upload uno per uno –

+0

può utilizzare questa libreria: https: //github.com/koush/ion – rafsanahmad007

risposta

3

Partenza questo tutorial - http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/

private class UploadFileToServer extends AsyncTask<Void, Integer, String> { 
     @Override 
     protected void onPreExecute() { 
      // setting progress bar to zero 
      progressBar.setProgress(0); 
      super.onPreExecute(); 
     } 

     @Override 
     protected void onProgressUpdate(Integer... progress) { 
      // Making progress bar visible 
      progressBar.setVisibility(View.VISIBLE); 

      // updating progress bar value 
      progressBar.setProgress(progress[0]); 

      // updating percentage value 
      txtPercentage.setText(String.valueOf(progress[0]) + "%"); 
     } 

     @Override 
     protected String doInBackground(Void... params) { 
      return uploadFile(); 
     } 

     @SuppressWarnings("deprecation") 
     private String uploadFile() { 
      String responseString = null; 

      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL); 

      try { 
       AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
         new ProgressListener() { 

          @Override 
          public void transferred(long num) { 
           publishProgress((int) ((num/(float) totalSize) * 100)); 
          } 
         }); 

       File sourceFile = new File(filePath); 

       // Adding file data to http body 
       entity.addPart("image", new FileBody(sourceFile)); 

       // Extra parameters if you want to pass to server 
       entity.addPart("website", 
         new StringBody("www.androidhive.info")); 
       entity.addPart("email", new StringBody("[email protected]")); 

       totalSize = entity.getContentLength(); 
       httppost.setEntity(entity); 

       // Making server call 
       HttpResponse response = httpclient.execute(httppost); 
       HttpEntity r_entity = response.getEntity(); 

       int statusCode = response.getStatusLine().getStatusCode(); 
       if (statusCode == 200) { 
        // Server response 
        responseString = EntityUtils.toString(r_entity); 
       } else { 
        responseString = "Error occurred! Http Status Code: " 
          + statusCode; 
       } 

      } catch (ClientProtocolException e) { 
       responseString = e.toString(); 
      } catch (IOException e) { 
       responseString = e.toString(); 
      } 

      return responseString; 

     } 

     @Override 
     protected void onPostExecute(String result) { 
      Log.e(TAG, "Response from server: " + result); 

      // showing the server response in an alert dialog 
      showAlert(result); 

      super.onPostExecute(result); 
     } 

    } 
+0

sopra i metodi httpclient vengono rimossi in marshmallow così posso 't do it –

2

Date un'occhiata a questo gist, vi si possono trovare piena exaple lavoro

Per prima cosa devi creare un RequestBody personalizzato con una strega di interfaccia aggiornerà la barra di avanzamento.

import com.squareup.okhttp.MediaType; 
import com.squareup.okhttp.RequestBody; 
import com.squareup.okhttp.internal.Util; 

import java.io.File; 
import java.io.IOException; 

import okio.BufferedSink; 
import okio.Okio; 
import okio.Source; 

public class ProgressRequestBody extends RequestBody { 


private static final int SEGMENT_SIZE = 2048; // okio.Segment.SIZE 

private final File file; 
private final ProgressListener listener; 
private final String contentType; 

public ProgressRequestBody(File file, String contentType, ProgressListener listener) { 
    this.file = file; 
    this.contentType = contentType; 
    this.listener = listener; 
} 


@Override 
public long contentLength() { 
    return file.length(); 
} 

@Override 
public MediaType contentType() { 
    return MediaType.parse(contentType); 
} 

@Override 
public void writeTo(BufferedSink sink) throws IOException { 
    Source source = null; 
    try { 
     source = Okio.source(file); 
     long total = 0; 
     long read; 

     while ((read = source.read(sink.buffer(), SEGMENT_SIZE)) != -1) { 
      total += read; 
      sink.flush(); 

      this.listener.transferred(total); 

     } 
    } finally { 
     Util.closeQuietly(source); 
    } 
} 

public interface ProgressListener { 
    void transferred(long num); 
} 

} 

è possibile copiare questa classe come è

Ora nella vostra attività o un frammento di implementare il ProgressListener dalla classe ProgressRequestBody e chiamare un seguenti metodi

public void uploadWithProgrss(File file) { 


    RequestBody requestBody = new MultipartBuilder() 

      //build multipart request 
      .type(MultipartBuilder.FORM) 

      //name= KEY for your param 
      //filename = VALUE of the param - in our case filename 
      //attach the custom ProgressRequestBody in form of (File file, String type, Interface ProgressRequestBody.ProgressListener) 
      //Set type depending on your content type if video set it to "video/mp4" or "image/jpeg" if image 
      .addPart(Headers.of("Content-Disposition", "form-data; name=\"digital_product[attachment]\"; filename=\"" + file.getName() + "\""), 
        new ProgressRequestBody(file, type2, this)) 

      //attach the rest of Request body parameters if any 
      .addPart(
        Headers.of("Content-Disposition", "form-data; name=\"digital_product[price]\""), 
        RequestBody.create(MediaType.parse("text/plain"), etPrice.getText().toString())) 
      .addPart(
        Headers.of("Content-Disposition", "form-data; name=\"digital_product[title]\""), 
        RequestBody.create(MediaType.parse("text/plain"), etCaption.getText().toString())) 
      .addPart(
        Headers.of("Content-Disposition", "form-data; name=\"digital_product[description]\""), 
        RequestBody.create(MediaType.parse("text/plain"), etCaption.getText().toString())) 
      .build(); 


    //Build your request 
    Request request = new Request.Builder() 
      //your url 
      .url(BuildConfig.API_URL + "api/v1/users/me/digital_products") 
      //request header if any 
      .addHeader("Authorization", "Bearer " + app.getAccessToken()) 
      //type of the request, i this case post request with request body 
      .post(requestBody) 
      .build(); 

    client.setReadTimeout(1, TimeUnit.MINUTES); 
    client.setConnectTimeout(1, TimeUnit.MINUTES); 
    client.setWriteTimeout(1, TimeUnit.MINUTES); 

    final Call call = client.newCall(request); 

    call.enqueue(new com.squareup.okhttp.Callback() { 
     @Override 
     public void onFailure(Request request, IOException e) { 

     } 

     @Override 
     public void onResponse(com.squareup.okhttp.Response response) throws IOException { 
      if (response.isSuccessful()) { 
       //Handle success 
      } else { 
       call.cancel(); 
       //handle error 
      } 
     } 
    }); 
} 

@Override 
public void transferred(final long num) { 
    //progress bar had to be updated from the UI thread 
    new Handler(activity.getMainLooper()).post(new Runnable() { 
     @Override 
     public void run() { 
      //just chacking if fragment is added 
      if (isAdded()) { 
       //Updating progress bar 
       progressBar.setProgress((int) ((num/(float) file.length()) * 100)); 
      } 
     } 
    }); 
} 
+1

Le risposte al solo collegamento sono generalmente [disapprovate] (http://meta.stackexchange.com/a/8259/204922) su Stack Overflow. Con il tempo è possibile che i collegamenti atrofia e diventino non disponibili, il che significa che la tua risposta è inutile per gli utenti in futuro. Sarebbe meglio se potessi fornire i dettagli generali della tua risposta nel tuo post effettivo, citando il tuo link come riferimento. – yennsarah

1
protected class upload_images extends AsyncTask<String, Integer, String> { 
    ProgressDialog progressDialog; 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     // showDialog(progress_bar_type); 
     progressDialog = new ProgressDialog(Accept_Report.this); 
     progressDialog.setCancelable(false); 
     // dialog.setCanceledOnTouchOutside(false); 
     progressDialog.setIndeterminate(false); 
     // progressDialog.setMax(100); 
     progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
     // progressDialog.setProgress(0); 
     progressDialog.setMax(100); 
     // progressDialog.setMessage("Loading ..."); 
     progressDialog.show(); 
     // ProgressBar progressBar = (ProgressBar)findViewById(R.id.progressBar2); 
    } 

    @Override 
    protected String doInBackground(String... params) { 
     URL url; 
     HttpURLConnection connection = null; 
     String http = Util.URL + "reports/media/create"; 
     try { 
      url = new URL(http); 
      connection = (HttpURLConnection) url.openConnection(); 
      . 
      . 
      . 
      connection.connect(); 

      ... 

      // you are doing this 

      // what is jsonParam ? 
      //byte[] payload = jsonParam.toString().getBytes("UTF-8"); 
      // how you gonna get content lenght from it? 

      int count = 0; 
      OutputStream wr = connection.getOutputStream(); 
      InputStream inputStream = null; 
      byte[] payload = jsonParam.toString().getBytes("UTF-8"); 
      int totalSze = payload.length; 
      Log.e("Total size ", "" + totalSze); 
      int bytesTransferred = 0; 
      int chunkSize = (2 * totalSze)/100; 
      boolean last_loop = false; 
      // publishProgress(0); 

      ... 
      // Do like this example 
      // getting file length 
      int lenghtOfFile = connection.getContentLength(); 
      // input stream to read file - with 8k buffer 
      InputStream input = new BufferedInputStream(url.openStream(), 8192); 
      // Output stream to write file 
      OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg"); 

      byte data[] = new byte[1024]; 
      long total = 0; 
      while ((count = input.read(data)) != -1) { 
       total += count; 
       // publishing the progress.... 
       // After this onProgressUpdate will be called 
       publishProgress((int) ((total * 100)/lenghtOfFile)); 

       // writing data to file 
       output.write(data, 0, count); 
      } 


     } catch (Exception e) { 
     } 
     return null; 
    } 

    @Override 
    protected void onProgressUpdate(Integer... values) { 
     super.onProgressUpdate(values); 
     // Log.e("dfsf",""+values[0]); 
     progressDialog.setProgress(values[0]); 
     // progressDialog.setProgress(values[0]); 

    } 

    @Override 
    protected void onPostExecute(String result) { 
     if (HttpResultimage == 204) { 
      progressDialog.dismiss(); 
     } 
    } 
} 
+0

Voglio caricare i dati sul server non sulla scheda SD –

+0

@Ajinkumar il suo esempio per il conteggio del numero di byte in trasferimento ...... e non hai spiegato cosa sia 'jsonParam' su quale base stai pubblicando i progressi. –

+0

Ho appena aggiunto alcuni commenti, sezione e immagine (stringa base64) a json array come questo {"media": [{"commenti": "", "sezione": 4, "immagini": "iVBORw0KGgoAAAANSUh"}]} . e aggiungi questo json array a jsonParam (variabile JSONObject) quindi invia il JSONObject al server –

1

http://samir-mangroliya.blogspot.in/p/android-asynctask-example.html

Si prega di aprire il link sopra, troverete il migliore risposta possibile.

+1

Le risposte di solo collegamento sono generalmente [disapprovate] (http://meta.stackexchange.com/a/8259/204922) su Overflow dello stack. Con il tempo è possibile che i collegamenti atrofia e diventino non disponibili, il che significa che la tua risposta è inutile per gli utenti in futuro. Sarebbe meglio se potessi fornire i dettagli generali della tua risposta nel tuo post effettivo, citando il tuo link come riferimento. – yennsarah

0

Assicurati di lavare all'interno del ciclo di tempo prima di aggiornare i progressi:

while (bytesTransferred < totalSze) { 
    ... 
    wr.flush(); 
    publishProgress((int)rounded); 
    ... 
}