Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem creating a Drawable from a SQLite Blob

Tags:

android

I'm caching image files as a blob in a SQLite database. I have a similar application on another platform that does the same thing with the same image files. The databases on both platforms report the exact same size for the same images. So I think, but can't guarantee, that the image data is getting into the database intact.

But when I try to create a Drawable, the console prints out "DEBUG/skia(267): --- decoder->decode returned false".

The steps are:

  1. Read the blob into a byte array.

    byte[] b = new byte[imageDataCursor.getInt(0)];

    b = imageDataCursor.getBlob(1);

  2. Create an InputStream from the byte array.

    ByteArrayInputStream is = new ByteArrayInputStream(b);

  3. Create a Drawable from the InputStream. (this is what creates the 'decoder' message above)

    Drawable drw = Drawable.createFromStream(is, "articleImage");

  4. Set the ImageView.image to the Drawable.

    imgView.setImageDrawable(drw);

So far, no joy. Any suggestions?

like image 219
deSelby Avatar asked Nov 14 '22 08:11

deSelby


1 Answers

I'll post my solution to help anyone with a similar problem.

I tried testing the byte array I'm reading from the database by writing it to a file and then viewing the file. It turns out that the blob data in the database is not complete - I get a few lines of the image, but not the entire image.

The solution involved creating a BufferedInputStream and a ByteArrayBuffer to read in the image from the remote server. The code to capture an image file from a remote server and create a byte array to be able to write it to a sqlite database looks like this:

             try {
             HttpGet getMethod=new HttpGet(url);
                HttpClient client=new DefaultHttpClient();
             HttpResponse response = client.execute(getMethod);
             HttpEntity entity = response.getEntity();
             InputStream in = entity.getContent();
             BufferedInputStream bis = new BufferedInputStream(in);
             ByteArrayBuffer baf = new ByteArrayBuffer(50);
             int current = 0;
             while ((current = bis.read()) != -1) {
              baf.append((byte) current);
             }
             byte[] b = baf.toByteArray();
           database.updateArticleWithImageData(b, imageKey);
         }
         catch (Throwable t) {
          android.util.Log.e("MyApp", "Exception fetching image file", t);
         }
like image 177
deSelby Avatar answered Nov 30 '22 22:11

deSelby