1

In my application, I load some URL from my database and store them in an ArrayList<Bitmap> to put them in a gallery. It works good, but it's very slow. The problem is that I load all the bitmap in the ArrayList before showing the images.

        try
        {
            JSONArray jArray = new JSONArray(result);
            for(int i=0;i<jArray.length();i++)
            {
                Temp = jArray.get(i).toString();

                HttpURLConnection connection = null;
                try 
                {
                    connection = (HttpURLConnection) new URL(Temp).openConnection();
                } 
                catch (MalformedURLException e) 
                {
                    e.printStackTrace();
                } 
                catch (IOException e) 
                {
                    e.printStackTrace();
                }
                connection.connect();
                InputStream input = connection.getInputStream();

                x = BitmapFactory.decodeStream(input);
                bitmapArray.add(x);
            }
        }
        return bitmapArray; // returning the array list with all the bitmaps inside

    protected void onPostExecute(ArrayList<Bitmap> donnees)
    {
        SetupInterface(); // This method sends the arraylist to an image adatper and display bitmaps to the screen.
    }

My problem is that SetupInterface() is called only when the array is full and returned. So when I open my activity, it takes about 4-5 seconds to display the gallery, because is has to load all the bitmaps inside the array before displying them. How to do it faster?

Adam Stelmaszczyk
  • 19,665
  • 4
  • 70
  • 110
francis lanthier
  • 101
  • 1
  • 1
  • 5

2 Answers2

0

Downloading images and decoding images take time. You know the content of the jArray already(at least the length, name of those images...). You should send the array w/ a default background image to the image adapter directly and use AsyncTask to load those actual images one by one.

Mac Wang
  • 331
  • 2
  • 4
0

In the start of an activity load and show only the first image. After your activity has been shown and all the initialization work is done, you will load the rest of images. You can:

  1. Load them one by one, in a background thread, using for example Handler or AsyncTask. The second will be easier to implement.
  2. Load the next image, when it has to be loaded, for example user clicks "next". It is called lazy loading.
Adam Stelmaszczyk
  • 19,665
  • 4
  • 70
  • 110
  • Could you give me an exemple of loading bitmaps one by one and sending them to an ImageAdapter? I triyed it by creating a new asynctask in the postexecute and calling my method again and again until the array is full... It's ptobably not the best way to do it... – francis lanthier Jan 17 '13 at 02:42