Amazon Gift Cards

Monday, October 12, 2009

How to insert image data to sqlite database in Android and how to retrieve it back

I ran across doing something that would required me to get an image from the internet and save it in the database instead of saving it in the file system then retrieving back the stored image from the database to be displayed in ImageView. Using other database server, we usually use blob to store binary data to the database, since SQLite has no field type we could use BLOB as its field type. Your create statement should appear like this
CREATE TABLE storedImages (_id INTEGER PRIMARY KEY, myImage BLOB)

To get the image from the internet and store it on our database
DefaultHttpClient mHttpClient = new DefaultHttpClient();
HttpGet mHttpGet = new HttpGet("your image url");
HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
if (mHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  HttpEntity entity = mHttpResponse.getEntity();
    if ( entity != null) {
      // insert to database
      ContentValues values = new ContentValues();
      values.put(MyBaseColumn.MyTable.ImageField, EntityUtils.toByteArray(entity));
      getContentResolver().insert(MyBaseColumn.MyTable.CONTENT_URI, values);
    }
}


Explanation
Create a new HTTP Client
DefaultHttpClient mHttpClient = new DefaultHttpClient();

Make a request to get our image
HttpGet mHttpGet = new HttpGet("your image url");
HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);


See if our request is a 200 or has an okay return status
if (mHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

Get the entity of our request
HttpEntity entity = mHttpResponse.getEntity();

Convert the content of the entity to byte array so that we could store it on our database
values.put(MyBaseColumn.MyTable.ImageField, EntityUtils.toByteArray(entity));

Insert our image to the databse
getContentResolver().insert(MyBaseColumn.MyTable.CONTENT_URI, values);

Retrieving the image back
Here is it assumed that you are using Custom CursorAdaptor, see Custom View in your ListActivity and Custom Adapter in Android
ImageView myImage = (ImageView) findViewById(R.id.myImage);
byte[] bb = cursor.getBlob(cursor.getColumnIndex(MyBaseColumn.MyTable.ImageField));
myImage.setImageBitmap(BitmapFactory.decodeByteArray(bb, 0, bb.length));


Explanation
Get the image back from our database
byte[] bb = cursor.getBlob(cursor.getColumnIndex(MyBaseColumn.MyTable.ImageField));

Decode our image to become a bitmap so that our imageView will display it properly
myImage.setImageBitmap(BitmapFactory.decodeByteArray(bb, 0, bb.length));

19 comments:

warrior said...

Hi,
Me new to android,actually i wanna know how to insert a blob type (image) into my database and retrieve it back to my application.
And the image is available as a bitmap to me,so just wanna insert into a field in my table called MY_TABLE and retrieve it back to my application.
Thank you

Unknown said...

Thanks for the tutorial!
It actually answered exactly what I wanted, unlike the google apis :O
and also taught me new useful stuff like the entity utils helper.

Sam said...

Thank you!
This is just what I've been looking for. This seems like a really good solution for image storage, why is it not better documented? Anyway, thanks :)

Anonymous said...

for my case don't work!!!
i try to develop in androis 2.2. Stept that i'm taking: getting a local picture as input stream convet it in byte[] to put it in sqllite the i get back the byte[] and try to render it in my layout. When i do the BitmapFactory.decodeByteArray i get null.

Please give me an advice.
10x for attention,
a.

monmonja said...

how did you save the byte[]? can you do a log if the input stream is really converting into byte[] and the problem is with before inserting into sqlite then retrieving it

Naraine said...

Can I know what is that MYBaseColumn.MyTable.MyImage

Gilles said...

Hello everybody,

I did your tutorial and it works very well.... But I have one problem.

I have 430 ko of picture but the data store in application is 7 Mo !!

I think that the memory use by the blob is my issue.

Can you say how can I compress the blob size ?

Thanks a lot (sorry for my english)

Anonymous said...

thank

Anonymous said...

hello,
i am new on android i want put image in list view through thr url.but how can some one help me.

martypantsROK said...

I've got a database but I currently store a path to the image.

Sometimes, however, when I scroll a list view, it's jerky and I wonder if it's because it has to read images each time.

Would stashing images as blobs in my database give me better performance?

Anyone have any thoughts on that?

Keerthy said...

Nice i too saw an example code for this in this link http://android-codes-examples.blogspot.com/2011/09/image-and-content-is-populated-from.html

Anonymous said...

hello there!
i'm developing an android app which is an extension of notepad app.. i need to store notes along with images from SD card or camera images.
now i have an activity which will take title and text notes.. i need to call images to this activity. now i have menu option which launches gallery and pick an image.. i'm using onActivityResult() method to return image... the code goes like this.

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SELECT_PHOTO) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);

imageView.setImageURI(selectedImageUri);

}
}

and this one method below returns the uri of the image..

public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

this code returns me a blank space in the imageview of the activity..

can any one tell me how to get through this.

Sweety said...

Hi,

I want to know what is "MyBaseColumn.MyTable' I get an error here

Anonymous said...

Hello everyone i want to store image in database which is get as input from user from gallery but not from internet....

Please help me out..... thanking you...

monmonja said...

@MehuL try
http://www.walletapp.net/crop-image

LeMat_Bin said...

Hi all,

Can I add animated gifs into a msqlite database and retrieve them with this way?

gouthami said...

what is mybasecolum.mytable.imagefield here?
hope mytable is the table name, but what is this mybasecolumn???

isisah said...

what is mybasecolumn.mytable??

isisah said...

byte[] blob = c.getBlob(c.getColumnIndex("image"));
ByteArrayInputStream inputStream = new ByteArrayInputStream(blob);
Bitmap bitmap = BitmapFactory.decodeByteArray(blob, 0, blob.length);
iview.setImageBitmap(bitmap);