Question

Hi I have one problem with ProgressDailog. I'm not able to set it properly in my code. In my code I'm getting URLs of images through JSON Array and downloading that images after that showing them into GridView and on click displaying selected image on next activity..This all work perfectly but the problem is As I'm using AsyncTask in my code it goes in background and fetch JSON, download images. I want to show ProgressBar till background process is completed and initialize the GridView after all images get downloaded ... Following is my code..

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

}

As I run this code the images get downloaded but not display on grid view and as I click on any Grid the image displays on next activity,,

ImageAdapter Class:

    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;
    }
}
Was it helpful?

Solution

You should Override onPreExecute() method before doInBackground method.

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

Then you should Override onPostExecute() method after doInBackground method.

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

You can find more information from this link

OTHER TIPS

Place your ProgressDialog in onPreExecute, hope this code helps you out :)

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

There are two more method in Async class i.e onPostExecute and onPreExecute method. in onPreExecute method you can write the following code

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

And onPostExecute method use pDialog.dismiss().

Use preExcecute to display progress dialog.

     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
   ...
   }

There is no need of writing Thread to show ProgressDialog.

Just simply you need to implement onPreExecute to show the dialog and onPostExecute to dismiss the dialog.

Just change your GetImageUrls method as below:

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

Start dialog in

onPreExecute() 

and dismiss it

onPostExecute()

The easiest way to show progress while doing background process!

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.


            }

        }

Use beelow code:

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

}

Try this

Activity class

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

                  }

}

Adapter class

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" />

you can use gridView instead of listview.

Use onPreExecute and onPostExecute method

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top