如何在AsyncTask中设置进度对话框

时间:2014-03-11 06:18:55

标签: android multithreading android-asynctask progressdialog

嗨我ProgressDailog有一个问题。我无法在我的代码中正确设置它。在我的代码中,我通过JSON数组获取图像的URL,然后下载图像,然后将它们显示在GridView中,然后点击在下一个活动中显示所选图像。这一切都很完美,但问题是因为我是在我的代码中使用AsyncTask进入后台并获取JSON,下载图像。我希望显示ProgressBar直到后台进程完成并在所有图像下载后初始化GridView ... 以下是我的代码..

    public class AndroidGridLayoutActivity extends Activity {

    public static  ImageAdapter img;
    public static  String[] imageurls;
    public static  GridView gridView;
    public static Bitmap bm[]=new Bitmap[4];
    private ProgressDialog pDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.grid_layout);
        // Showing progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setMax(5);
        pDialog.setMessage("Loading...");
        pDialog.setCancelable(true);
        pDialog.show();
        new GetImageUrls().execute();
        Thread thread = new Thread()
        {
            @Override
            public void run() {
                int count=0;
                while(count<3) {
                    try {

                            sleep(1000);
                            count++;
                        }
                    catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if(pDialog != null && pDialog.isShowing()){
                    pDialog.dismiss();
                }
                new GetImageUrls().execute();
            }
        };

        thread.start();
        gridView = (GridView) findViewById(R.id.grid_view);
        // Instance of ImageAdapter Class
        img = new ImageAdapter(AndroidGridLayoutActivity.this,bm);
        gridView.setAdapter(img);
        /**
         * On Click event for Single Gridview Item
         * */
        gridView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {
                // Sending image id to FullScreenActivity
                Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
                // passing array index
                i.putExtra("id", position);
                startActivity(i);
            }
        });
    }   
    public class GetImageUrls  extends AsyncTask<Void, Void, Void>
    {
        Context context = getBaseContext();
        private static final String url= "http://xxx.xxx.x.xxx/demo/test.json";
        private static final String MAIN = "mainCategory";
        private static final String SUB = "mcatimage";
        JSONArray loginjsonarray=null;

        protected Void doInBackground(Void... arg) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();
             // Making a request to url and getting response
            String jsonstr = sh.makeServiceCall(url, ServiceHandler.POST, null);
            if(jsonstr!=null)
            {
                try {
                        JSONObject jsonObj =new JSONObject(jsonstr);
                        loginjsonarray=jsonObj.getJSONArray(MAIN);
                        imageurls=new String[loginjsonarray.length()];
                        for(int i=0;i<loginjsonarray.length();i++)
                        {
                            JSONObject l=loginjsonarray.getJSONObject(i);
                            imageurls[i]=l.getString(SUB);
                        }

                        for(int i=0;i<imageurls.length;i++)
                        {   
                            bm[i]=DownloadImage(imageurls[i]);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
            }else{
                Toast.makeText(context,"Check your Internet Connection",Toast.LENGTH_SHORT).show();
            }
            return null;
        }

        public Bitmap DownloadImage(String STRURL) {
            Bitmap bitmap = null;
            InputStream in = null;       
            try {
                    int response = -1;
                    URL url = new URL(STRURL);
                    Log.d("DownloadImage: ", url.toString());
                    URLConnection conn = url.openConnection();
                    if (!(conn instanceof HttpURLConnection))             
                        throw new IOException("Not an HTTP connection");
                    try{
                        HttpURLConnection httpConn = (HttpURLConnection) conn;
                        httpConn.setAllowUserInteraction(false);
                        httpConn.setInstanceFollowRedirects(true);
                        httpConn.setRequestMethod("GET");
                        httpConn.connect();
                        response = httpConn.getResponseCode();  
                        Log.d("DownloadImage response: ", Integer.toString(response));
                        if (response == HttpURLConnection.HTTP_OK) {
                            in = httpConn.getInputStream();
                            Log.d("DownloadImage: ", in.toString());
                        }                    
                    } catch (Exception ex) {
                        throw new IOException("Error connecting"); 
                    }
                    bitmap = BitmapFactory.decodeStream(in);
                    Log.d("DownloadImage Bitmap: ", bitmap.toString());
                    in.close();
                }catch (IOException e1) {
                    e1.printStackTrace();
                }
            return bitmap; 
        }
    }

}

当我运行此代码时,图像会被下载但不会显示在网格视图上,当我点击任何网格时,图像会显示在下一个活动中,

ImageAdapter类:

    public class ImageAdapter extends BaseAdapter {
    private Context mContext;
    public static Bitmap adapterbm[]=new Bitmap[4];
    ImageView imageView;
    public static  String[] imageurls;

    // Constructor
    public ImageAdapter(Context c, Bitmap[] bm){
        mContext = c;
        adapterbm = bm; 
    }


    public ImageAdapter(Context c) {
        mContext = c;
    }


    @Override
    public int getCount() {
        return adapterbm.length;
    }

    @Override
    public Object getItem(int position) {
        return adapterbm[position];
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        imageView = new ImageView(mContext);
        imageView.setImageBitmap(adapterbm[position]);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
        return imageView;
    }
}

10 个答案:

答案 0 :(得分:2)

你应该在doInBackground方法之前覆盖onPreExecute()方法。

ProgressDialog myPd_bar;

        @Override
        protected void onPreExecute() {
        // TODO Auto-generated method stub
          myPd_bar=new ProgressDialog(AndroidGridLayoutActivity.this);
          myPd_bar.setMessage("Loading....");
          myPd_bar.setTitle(title);
          myPd_bar.show();
          super.onPreExecute();
        }

然后你应该在doInBackground方法之后覆盖onPostExecute()方法。

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

您可以在此link

中找到更多信息

答案 1 :(得分:1)

将您的ProgressDialog放入onPreExecute,希望此代码可以帮助您:)

private ProgressDialog pdia;

@Override
protected void onPreExecute(){ 
   super.onPreExecute();
        pdia = new ProgressDialog(yourContext);
        pdia.setMessage("Loading...");
        pdia.show();    
}

@Override
protected void onPostExecute(String result){
   super.onPostExecute(result);
        pdia.dismiss();
}

答案 2 :(得分:1)

Async类中还有两种方法,即onPostExecute和onPreExecute方法。在onPreExecute方法中,您可以编写以下代码

pDialog = new ProgressDialog(this);
        pDialog.setMax(5);
        pDialog.setMessage("Loading...");
        pDialog.setCancelable(true);
        pDialog.show();

onPostExecute方法使用pDialog.dismiss()。

答案 3 :(得分:1)

使用preExcecute显示进度对话框。

     ProgressDialog pDialog; 
public class GetImageUrls  extends AsyncTask<Void, Void, Void>{
@Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Activity.this);
        pDialog.setMessage("Loading. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }
  @Override
   protected Void doInBackground(Void... arg)
   {....
   } 
  @Override
   protected postExcecute()
   {
   pDialog.dismiss(); 
   ....//display UI
   ...
   }

答案 4 :(得分:1)

无需撰写Thread来展示ProgressDialog

只需要实现onPreExecute来显示对话框,onPostExecute来解除对话框。

只需更改GetImageUrls方法,如下所示:

public class GetImageUrls  extends AsyncTask<Void, Void, Void>
{
    Context context = getBaseContext();
    private static final String url= "http://xxx.xxx.x.xxx/demo/test.json";
    private static final String MAIN = "mainCategory";
    private static final String SUB = "mcatimage";
    JSONArray loginjsonarray=null;

@Override
protected void onPreExecute(){ 
   super.onPreExecute();
         pDialog = new ProgressDialog(this);
    pDialog.setMax(5);
    pDialog.setMessage("Loading...");
    pDialog.setCancelable(true);
    pDialog.show();
}
    protected Void doInBackground(Void... arg) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();
         // Making a request to url and getting response
        String jsonstr = sh.makeServiceCall(url, ServiceHandler.POST, null);
        if(jsonstr!=null)
        {
            try {
                    JSONObject jsonObj =new JSONObject(jsonstr);
                    loginjsonarray=jsonObj.getJSONArray(MAIN);
                    imageurls=new String[loginjsonarray.length()];
                    for(int i=0;i<loginjsonarray.length();i++)
                    {
                        JSONObject l=loginjsonarray.getJSONObject(i);
                        imageurls[i]=l.getString(SUB);
                    }

                    for(int i=0;i<imageurls.length;i++)
                    {   
                        bm[i]=DownloadImage(imageurls[i]);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
        }else{
            Toast.makeText(context,"Check your Internet Connection",Toast.LENGTH_SHORT).show();
        }
        return null;
    }
  @Override
  protected void onPostExecute(String result){
       super.onPostExecute(result);
        pDialog.dismiss();
   }

答案 5 :(得分:0)

中启动对话框
onPreExecute() 

并解雇它

onPostExecute()

答案 6 :(得分:0)

在进行后台处理时显示进度的最简单方法!

private class GetImageUrls extends AsyncTask<String, String , String> {

        ProgressDialog progressDialog;
        @Override
        protected void onPreExecute() {
        progressDialog = ProgressDialog.show(this,null, "Loading ...", true);
        progressDialog.setCancelable(true);

         }
        @Override
        protected String doInBackground(String... arg0) {
                //background process

        }

        protected void onProgressUpdate(String... str) {

        }

        protected void onPostExecute(String result) {
               progressDialog.dismiss(); // once process complete it will dismiss.


            }

        }

答案 7 :(得分:0)

使用beelow代码:

    ProgressDialog mProgressDialog;


     public class GetImageUrls  extends AsyncTask<Void, Void, Void>
        {
            Context context = getBaseContext();
            private static final String url= "http://xxx.xxx.x.xxx/demo/test.json";
            private static final String MAIN = "mainCategory";
            private static final String SUB = "mcatimage";
            JSONArray loginjsonarray=null;

    @Override
    protected void onPreExecute(){ 
       super.onPreExecute();
          mProgressDialog = ProgressDialog.show(AndroidGridLayoutActivity.this,
                        "", "Loading...");
                mProgressDialog.setCancelable(false);
    }

            protected Void doInBackground(Void... arg) {
                // Creating service handler class instance
                ServiceHandler sh = new ServiceHandler();
                 // Making a request to url and getting response
                String jsonstr = sh.makeServiceCall(url, ServiceHandler.POST, null);
                if(jsonstr!=null)
                {
                    try {
                            JSONObject jsonObj =new JSONObject(jsonstr);
                            loginjsonarray=jsonObj.getJSONArray(MAIN);
                            imageurls=new String[loginjsonarray.length()];
                            for(int i=0;i<loginjsonarray.length();i++)
                            {
                                JSONObject l=loginjsonarray.getJSONObject(i);
                                imageurls[i]=l.getString(SUB);
                            }

                            for(int i=0;i<imageurls.length;i++)
                            {   
                                bm[i]=DownloadImage(imageurls[i]);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                }else{
                    Toast.makeText(context,"Check your Internet Connection",Toast.LENGTH_SHORT).show();
                }
                return null;
            }

            public Bitmap DownloadImage(String STRURL) {
                Bitmap bitmap = null;
                InputStream in = null;       
                try {
                        int response = -1;
                        URL url = new URL(STRURL);
                        Log.d("DownloadImage: ", url.toString());
                        URLConnection conn = url.openConnection();
                        if (!(conn instanceof HttpURLConnection))             
                            throw new IOException("Not an HTTP connection");
                        try{
                            HttpURLConnection httpConn = (HttpURLConnection) conn;
                            httpConn.setAllowUserInteraction(false);
                            httpConn.setInstanceFollowRedirects(true);
                            httpConn.setRequestMethod("GET");
                            httpConn.connect();
                            response = httpConn.getResponseCode();  
                            Log.d("DownloadImage response: ", Integer.toString(response));
                            if (response == HttpURLConnection.HTTP_OK) {
                                in = httpConn.getInputStream();
                                Log.d("DownloadImage: ", in.toString());
                            }                    
                        } catch (Exception ex) {
                            throw new IOException("Error connecting"); 
                        }
                        bitmap = BitmapFactory.decodeStream(in);
                        Log.d("DownloadImage Bitmap: ", bitmap.toString());
                        in.close();
                    }catch (IOException e1) {
                        e1.printStackTrace();
                    }
                return bitmap; 
            }
        }

    @Override
    protected void onPostExecute(){
         if (mProgressDialog.isShowing())
                        mProgressDialog.dismiss();
                }
    }

}

答案 8 :(得分:0)

试试这个

活动类

package com.example.imagelist;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

    ItemsAdapter adapter;
    ListView list;
    ProgressDialog myPd_bar;
    static String img_url;
    private String strJson1 = "";
    private String url = "http://........................";
    ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion > android.os.Build.VERSION_CODES.FROYO) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .detectAll().penaltyLog().build();
            StrictMode.setThreadPolicy(policy);
        }
        /*
        int images[] = {R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d};
        */
        list = (ListView) findViewById(R.id.listView1);
        accessWebService();

    }

    // Async Task to access the web
            private class JsonReadTask extends AsyncTask<String, Void, String> {

                @Override
                protected void onPreExecute() {
                    // TODO Auto-generated method stub
                    myPd_bar=new ProgressDialog(MainActivity.this);
                    myPd_bar.setMessage("Loading....");
                    myPd_bar.setTitle(null);
                    myPd_bar.show();
                    super.onPreExecute();
                }

                @Override
                protected String doInBackground(String... params) {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost(params[0]);
                    try {
                        HttpResponse response = httpclient.execute(httppost);
                        strJson1 = inputStreamToString(
                                response.getEntity().getContent()).toString();
                    }

                    catch (ClientProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                private StringBuilder inputStreamToString(InputStream is) {
                    String rLine = "";
                    StringBuilder answer = new StringBuilder();
                    BufferedReader rd = new BufferedReader(new InputStreamReader(is));

                    try {
                        while ((rLine = rd.readLine()) != null) {
                            answer.append(rLine);
                        }
                    }

                    catch (IOException e) {
                        // e.printStackTrace();
                        Toast.makeText(getApplicationContext(),
                                "Error..." + e.toString(), Toast.LENGTH_LONG).show();
                    }
                    return answer;
                }

                @Override
                protected void onPostExecute(String result) {
                    ListDrwaer();
                    myPd_bar.dismiss();
                }
            }// end async task

            public void accessWebService() {
                JsonReadTask task = new JsonReadTask();
                // passes values for the urls string array
                task.execute(new String[] { url });
            }

            //build hash set for list view    
             public void ListDrwaer(){

                 List<String> listImg = new ArrayList<String>();

                      try{
                            JSONObject jsonResponse = new JSONObject(strJson1);
                            JSONArray jsonMainNode = jsonResponse.optJSONArray("bank");

                        for(int i = 0; i<jsonMainNode.length();i++){
                            JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                                 img_url = jsonChildNode.optString("logo");

                                 listImg.add(img_url);
                                // Log.d("URL", img_url);

                        }

                        ItemsAdapter adapter = new ItemsAdapter(getApplicationContext(), listImg);
                        list.setAdapter(adapter);

                        }
                        catch(JSONException e){
                            Toast.makeText(getApplicationContext(),"Connection Error...", Toast.LENGTH_LONG).show();
                        }

                  }

}

适配器类

package com.example.imagelist;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;

public class ItemsAdapter extends ArrayAdapter<Integer> {

    private final Context context;
    ImageView imageView;

    List<String> listImg;

    ItemsAdapter(Context context, List<String> listImg) {
        super(context, R.layout.items_list_item);
        this.context = context;
        this.listImg = listImg;
}

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return listImg.size();
    }

    @Override
    public Integer getItem(int arg0) {
        // TODO Auto-generated method stub
        return arg0;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        final String text = listImg.get(position);

            LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View rowView = convertView;
            if (null == convertView)
                rowView = inflater.inflate(R.layout.items_list_item, parent, false);
            imageView = (ImageView) rowView.findViewById(R.id.list_item_image);
            Bitmap bitmap;
            URL imageURL = null;

        try {
            imageURL = new URL(text);
        }

        catch (MalformedURLException e) {
            e.printStackTrace();
        }

        try {
            HttpURLConnection connection = (HttpURLConnection) imageURL
                    .openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream inputStream = connection.getInputStream();

            bitmap = BitmapFactory.decodeStream(inputStream);// Convert to bitmap
            imageView.setImageBitmap(bitmap);
        } catch (IOException e) {

            e.printStackTrace();
        }

            return rowView ;
        }
}

<强> activity_main.xml中

 <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >
    </ListView>

<强> list_item.xml

 <ImageView
        android:id="@+id/list_item_image"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" />

您可以使用gridView而不是listview。

答案 9 :(得分:0)

使用onPreExecute和onPostExecute方法