简体   繁体   中英

Show progress bar while downloading JSON - Android

I am downloading a very huge JSON and it takes a lot of time.
I want to show the percentage of data I have downloaded.

I searched and found how to display progress if downloading a file but not JSON.

Here is how I am downloading 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;
    }

You better to use AsyncTask to download data. There is a sample code below. I did not test it but it should work.

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();
    }
}

You can call it from your activity, fragment etc.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM