Problem on inserting & retrieve image data in sqlite database using android
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.setAllowUserInte开发者_开发问答raction(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
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.
精彩评论