How can i add image to sqlite database and then retrieve ? using Content Provider
*i want to get this image that i loaded from gallery of taken by camera to be stored in the database to use it in another activities *
How can i add image to sqlite database and then retrieve ? using Content Provider
*i want to get this image that i loaded from gallery of taken by camera to be stored in the database to use it in another activities *
You could save the path to the image in the databse. Then in next activity, retrieve it and if the file exists display it...
When user selected image from gallery, i guess you get the URI from onActivityResult()
. You just need to get the path to it using a code like this one :
private String getRealPathFromURI(Uri contentUri) {
String[] store = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(mContext, contentUri, store, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
if (cursor != null ) {
cursor.close();
}
return result;
}
Just save the path in your database the way you want.
Later on, try to get the file. If file exists, update your ImageView
File file = new File(savedPath);
if(file.exists){
// load image in your imageView
Bitmap mBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
yourImageView.setImageBitmap(mBitmap);
}
Images are stored as BLOB's in Sqlitedatabase.
For saving an image in to Database
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getItemname());
values.put(KEY_DESCRIPTION, contact.getDescription());
Log.i("","Adding image of Type Bitmap"+contact.getImage());
if(contact.getImage()!=null) {
values.put(KEY_IMAGE, Utility.getBytes(contact.getImage()));
}
Where getBytes(Bitmap) would be :
public static byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, stream);
return stream.toByteArray();
}
While fetching an Image from the Database :
if(cursor.getBlob(3)!=null)
{
contact.setImage(Utility.getPhoto(cursor.getBlob(3));
}
else
{
contact.setImage(null);
}
And getPhoto(BLOB) would be:
// convert from byte array to bitmap
public static Bitmap getPhoto(byte[] image) {
return BitmapFactory.decodeByteArray(image, 0, image.length);
}