从Web加载JSON时显示进度条

时间:2015-02-15 06:02:23

标签: android

我想为Json下载一个进度条  下载开始时:

我想为用户显示一个对话框窗口。 下载后,进度条消失。

java code:

public class GetJsonTask extends AsyncTask<String, Void, String>
    {
        protected void onPreExecute() 
        { 
            progressDialog = new ProgressDialog(MainActivity.this); 
            progressDialog.setTitle("Processing...");
            progressDialog.setMessage("Please wait...");
            progressDialog.setCancelable(true);
            progressDialog.show();
        }



        @Override
        protected String doInBackground(String... urls) {
            // TODO Auto-generated method stub
            return getJson(urls[0]);
        }
        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
             progressDialog.dismiss();
            try {

               jsonArray=new JSONArray(result);

                 JSONObject number = jsonArray.getJSONObject(0);


                            download(); 


        }
        catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
   Log.e("aa", "erroor"+e.toString());
        }
    }

    }


  public  int download() throws JSONException
    {


        final Dialog dialog = new Dialog(context);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.progress_activity);
        final ProgressBar progressBar;
        Handler handler=new Handler();
        progressBar=(ProgressBar) dialog.findViewById(R.id.progress);
        progressBar.setMax(7);
        dialog.show();
         for( i=1;i<7;i++)
         {
         JSONObject object = jsonArray.getJSONObject(i);
         object = jsonArray.getJSONObject(i);
           title[i-1]=object.getString("title");
            qustion[i-1]=object.getString("qustion");

            handler.post(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    progressBar.setProgress(i);

                }
            });


         }
         handler.post(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                progressBar.setVisibility(View.GONE);
            }
        });

但是当程序执行时 不显示进度条 (进度条是GONE)

有什么问题?

1 个答案:

答案 0 :(得分:1)

在asyncTask类中(正如您在评论中所说),在onPreExecute方法中显示您的进度,如下所示:

protected void onPreExecute() {
            progressBar = new ProgressDialog(YourActivity.this);
            progressBar.setMessage("Downloading...");
            progressBar.show();
        }

并在onPostExecute方法中解除它:

protected void onPostExecute() {
            if (progressBar.isShowing()) {
                progressBar.dismiss();
            }
        }