下载JSON时显示进度条 - Android

时间:2015-12-07 07:14:41

标签: java android json http download

我正在下载一个非常庞大的JSON,需要花费很多时间 我想显示我下载的数据百分比。

我搜索并找到了如何在下载文件但不是JSON时显示进度。

以下是我如何下载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 个答案:

答案 0 :(得分:0)

您最好使用AsyncTask下载数据。下面有一个示例代码。我没有测试它,但它应该工作。

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

您可以从您的活动,片段等中调用它。

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