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));
2 comments:
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
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.
Post a Comment