0

I need to fetch images from url's and Load them into gridview. I am getting network on Main thread exception in the getView method of my ImageAdapter class which extends Base Adapter. How can i solve this using a Separate thread or an Async Task.

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

    ImageView imageView;

    try {

            URL url = new URL(Product_ItemsURLs[position]);

            InputStream content = (InputStream)url.getContent();

            Drawable drawable = Drawable.createFromStream(content , "src"); 

            if (convertView == null)
            {
                imageView = new ImageView(mContext);
                imageView.setLayoutParams(new GridView.LayoutParams(380,380));
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                imageView.setPadding(10, 10, 10, 10);
            }
            else
            {
                imageView = (ImageView) convertView;
            }

            imageView.setImageDrawable(drawable);

            return imageView;

        } catch (MalformedURLException e) {

            e.printStackTrace();
            return null;

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }

}
SKK
  • 5,261
  • 3
  • 27
  • 39
  • Usually you get this error when you are performing some n/w related operation in main thread try to use Async task or use thread – Akshay Oct 17 '12 at 10:07
  • 1
    Use `AsyncTask` to load images into your `GridView` – Praveenkumar Oct 17 '12 at 10:08
  • I moved the code to an Async Task and Now i am getting array index out of bound exception. – SKK Oct 17 '12 at 10:30
  • In which part of the code? We really need your new code to answer that (or really a new question since the original issue is now fixed, and question answered). – athor Oct 17 '12 at 10:37

1 Answers1

0

The line below is what is causing the issue. It's performing a network operation. From honeycomb onwards android doesn't allow network operations on the UI Thread.

Drawable drawable = Drawable.createFromStream(content , "src");

You need to use an Asynctask to download the drawable, and set the drawable to the view in your onPostExecute (which runs on the UI Thread).

Akshay
  • 2,506
  • 4
  • 34
  • 55
athor
  • 6,848
  • 2
  • 34
  • 37