tags:

views:

26

answers:

1

Hi all

i am new to android development.currently i am facing a problem while inserting/retrieving image to sqlite database using android.

//code for inserting image InputStream in = OpenHttpConnection(imgurl);

byte[] bb = new byte[in.available()];

in.read(bb);//here the length of bb is 2040

//update query

myDataBase.execSQL("Update Product SET Image='"+bb+"' Where CatPID='"+pcpid+"'");

//function OpenHttpConnection private InputStream OpenHttpConnection(String urlString) throws IOException { InputStream in = null; int response = -1;

    URL url = new URL(urlString); 
    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();                 
        if (response == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();                                 
        }                     
    }
    catch (Exception ex)
    {
        throw new IOException("Error connecting");            
    }
    return in;     
}

//code for retrieve image from database

byte[] bb = cursor.getBlob(cursor.getColumnIndex("Image"));//here length is only 12

ByteArrayInputStream imageStream = new ByteArrayInputStream(bb);

Bitmap theImage = BitmapFactory.decodeStream(imageStream);

img.setImageBitmap(theImage);

but no image is shown.Log shows "Factory returned null"

can anyone help me to find out where i am wrong and provide me code snippet of a working solution?

thanks in advance

A: 

You may use decodeByteArray:

final byte[] image_byte = c.getBlob(0);
Bitmap image_bitmap = BitmapFactory.decodeByteArray(image_byte, 0, image_byte.length);

and possibly Bitmap.createScaledBitmap() to rescale it if needed.

Rorist
Hi Rorist thanks for your response.I have also tried this but still facing the same problem.Log says "SKImageDecoder:Factory returned null".Is there any problem in my image inserting technique?
outsider
I'm not sure you are actually getting the correct image size using InputStream.available() as it's stated in the doc that's an estimated value. Then, you are not garantie at all to have the whole image in one read() call. You should loop until read() return -1. Here is the class I made for downloading files: http://github.com/rorist/android-network-discovery/blob/master/src/info/lamatricexiste/network/Network/DownloadFile.java
Rorist