2015-12-07 1 views
0

Je télécharge un très grand JSON et cela prend beaucoup de temps.
Je souhaite afficher le pourcentage de données que j'ai téléchargées.Afficher la barre de progression pendant le téléchargement JSON - Android

J'ai cherché et trouvé comment afficher la progression si je télécharge un fichier mais pas JSON.

Voici comment je suis le téléchargement JSON

private String getStringFromURL(String url) { 
     String string = null; 

     try { 

      HttpClient client = new DefaultHttpClient(); 

      url = url.replace(" ", "%20"); 
      url = url.replace("|", "%7C"); 
      HttpGet get = new HttpGet(url); 
      HttpResponse response = client.execute(get); 
      if (response.getStatusLine().getStatusCode() == 200) { 
       String result = EntityUtils.toString(response.getEntity(), 
         HTTP.UTF_8); 
       if (result.toLowerCase().contains("invalid")) 
        return null; 
       result = result.replace("\r", ""); 
       result = result.replace("\n", "").replace("\t", "\\t") 
         .replace("\b", "\\b").replace("\f", "\\f") 
         .replace("&", "\\&").replace("\'", "\\'") 
         .replace(";", "\\;").replace("?", "\\?") 
         .replace("*", "\\*"); 
       string = result; 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return string; 
    } 
+1

Voir [Android du fichier de téléchargement en montrant la barre de progression] (http://www.androidhive.info/2012/04/android -downloading-fichier-en-montrant-barre de progression /) tutoriel qui aide probablement –

+0

utiliser ceci: '(int) ((total * 100)/lenghtOfFile)' – Amy

+0

@ ρяσѕρєяK Je l'ai regardé mais je n'ai pas pu publier de progrès ne sais pas pourquoi, s'il vous plaît voir http://stackoverflow.com/q/34134013/3828908 – Salmaan

Répondre

0

Vous feriez mieux d'utiliser AsyncTask pour télécharger des données. Il y a un exemple de code ci-dessous. Je ne l'ai pas testé mais ça devrait marcher.

private class FetchJsonTask extends AsyncTask<Void, Void, String> { 
    private ProgressDialog progressDialog; 
    private Context context; 

    public FetchJsonTask(Context context) { 
     this.context = context; 
    } 

    @Override 
    protected void onPreExecute() { 
     // set up progress dialog 
     progressDialog = new ProgressDialog(context); 
     progressDialog.setIndeterminate(true); 
     progressDialog.setMessage("Please wait..."); 

     // show it 
     progressDialog.show(); 
    } 

    @Override 
    protected String doInBackground(Void... params) { 
     // These two need to be declared outside the try/catch 
     // so that they can be closed in the finally block. 
     HttpURLConnection urlConnection = null; 
     BufferedReader reader = null; 

     // Will contain the raw JSON response as a string. 
     String jsonStr = null; 

     try { 
      // Construct the URL somehow 
      URL url = createURL(); 

      // Create the request to MuslimSalat.com, and open the connection 
      urlConnection = (HttpURLConnection) url.openConnection(); 
      urlConnection.setRequestMethod("GET"); 
      urlConnection.connect(); 

      // Read the input stream into a String 
      InputStream inputStream = urlConnection.getInputStream(); 
      StringBuffer buffer = new StringBuffer(); 
      if (inputStream == null) { 
       // Nothing to do. 
       return null; 
      } 
      reader = new BufferedReader(new InputStreamReader(inputStream)); 

      String line; 
      while ((line = reader.readLine()) != null) { 
       // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) 
       // But it does make debugging a *lot* easier if you print out the completed 
       // buffer for debugging. 
       buffer.append(line + "\n"); 
      } 

      if (buffer.length() == 0) { 
       // Stream was empty. No point in parsing. 
       return null; 
      } 
      jsonStr = buffer.toString(); 
     } catch (IOException e) { 
      Log.e(LOG_TAG, "Error ", e); 
      // If the code didn't successfully get the data, there's no point in attemping 
      // to parse it. 
      return null; 
     } finally{ 
      if (urlConnection != null) { 
       urlConnection.disconnect(); 
      } 
      if (reader != null) { 
       try { 
        reader.close(); 
       } catch (final IOException e) { 
        Log.e(LOG_TAG, "Error closing stream", e); 
       } 
      } 
     } 

     return jsonStr; 
    } 

    @Override 
    protected void onPostExecute(String jsonString) { 
     // jsonString is your result use it somehow. 
     Log.d(LOG_TAG, "Json result: " + jsonString); 

     // dismiss the progress because downloading process is finished. 
     progressDialog.dismiss(); 
    } 
} 

Vous pouvez l'appeler de votre activité, etc. fragment

FetchJsonTask fetchJsonTask = new FetchJsonTask(context); 
fetchJsonTask.execute(); 
+0

Comment puis-je obtenir le pourcentage de données téléchargées? – Salmaan

+0

Vous pouvez vérifier [ce fil] (http://stackoverflow.com/a/3028660/4557274). Il y a plus d'informations à ce sujet. – sembozdemir