如何在下载json时更新progressBar

时间:2015-02-15 09:46:31

标签: android

我想下载一个文件Jason 我为Jason下载了一个进度条.. 我的问题是进度条没有更新。 正确下载但不更新进度条 问题是什么 ? java代码:

    public class GetJsonTask extends AsyncTask<String, String, String>
    {
        @Override
          protected void onProgressUpdate(String... progress) {
                // setting progress percentage

                dialog.setProgress(Integer.parseInt(progress[0]));
           }
        protected void onPreExecute() 
        { 
            dialog = new ProgressDialog(MainActivity.this); 
            dialog.setMessage("Downloading " +  " from the server. Please wait.");
            dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            dialog.setCancelable(false); 
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
        }



        @Override
        protected String doInBackground(String... urls) {
            // TODO Auto-generated method stub
             try {
                    InputStream inputStream = null;
                    DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(urls[0]);
                    HttpResponse httpResponse = defaultHttpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    inputStream = httpEntity.getContent();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    byte data[] = new byte[1024];

                    long total = 0;

                    while ((count = reader.read()) != -1) {
                        total += count;
                        // publishing the progress....
                        // After this onProgressUpdate will be called
                        publishProgress(""+(int) ((total*100) / 10000) );




                    }
                    inputStream.close();
                    String result = sb.toString();

                    return result;
                } catch (Exception ex) {
                      Log.e("aa2", "erroor2"+ex.toString());
                    return null;
                }





        }
        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);

             dialog.dismiss();
            }
}

1 个答案:

答案 0 :(得分:0)

正如this answer中所述,您应该设置setIndeterminate(false)