2

I am writing a little picture frame app for android that is using opengl for part of the UI. This portion needs to get images from flickr and load them into a texture. The code I have below is functional most of the time, but it has a Thread.sleep() kludge in between getting the input stream from the connection and the bitmap factory decoding the stream:

            URL url = new URL("http://farm5.static.flickr.com/4132/5168797476_7a85deb2be_b.jpg");
            URLConnection con = url.openConnection();
            InputStream is = con.getInputStream();
            Thread.sleep(250); //What am I actually waiting for?
            sourceBitmap = BitmapFactory.decodeStream(is);

How do I get around using the sleep() method in favor of something that makes logical sense?

I am testing on a samsung galaxy tab not in the emulator

Mr Bell
  • 9,228
  • 18
  • 84
  • 134

2 Answers2

0

I think you should implement AsyncTask. Refer this: http://developer.android.com/resources/articles/painless-threading.html

public void onClick(View v) {
  new DownloadImageTask().execute("http://example.com/image.png");
}

private class DownloadImageTask extends AsyncTask<string, void,="" bitmap=""> {
     protected Bitmap doInBackground(String... urls) {
         return loadImageFromNetwork(urls[0]);
     }

     protected void onPostExecute(Bitmap result) {
         mImageView.setImageBitmap(result);
     }
 }

I hope it helps you !!

Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295
  • Downloading the images asynchronously is of course a good idea, however, it doesn't really address the actual question – Mr Bell Dec 02 '10 at 03:41
0

This seems less than ideal, but if you read the stream byte by byte into a buffer and then pass the byte array to the BitmapFactory it works correctly.

            URL url = new URL("http://farm5.static.flickr.com/4132/5168797476_7a85deb2be_b.jpg");
            URLConnection con = url.openConnection();
            con.connect();
            int fileLength = con.getContentLength();
            InputStream is = con.getInputStream();
            byte[] bytes = new byte[fileLength];
            for(int i=0;i<fileLength;i++) {
                bytes[i] = (byte)is.read();
            }
            sourceBitmap = BitmapFactory.decodeByteArray(bytes, 0, fileLength);

I tried reading the bytes into the buffer all at once with is.read(bytes, 0, fileLength) but it did not reliably fill the buffer completely unless I waited a moment before calling the read. Is it possible that android implementation of InputStream's read method is flawed causing the BitmapFactory's decodeStream method to fail due to incomplete data?

Mr Bell
  • 9,228
  • 18
  • 84
  • 134