-1

How can i add image to sqlite database and then retrieve ? using Content Provider enter image description here

*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 *

Mohamed Farahat
  • 751
  • 1
  • 7
  • 12
  • Hi Mohamed, You have to use Blobs. See answer below http://stackoverflow.com/questions/11790104/how-to-storebitmap-image-and-retrieve-image-from-sqlite-database-in-android http://stackoverflow.com/questions/9357668/how-to-store-image-in-sqlite-database – Ruchira Randana Oct 17 '16 at 17:05

2 Answers2

-1

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);
}
HelloSadness
  • 945
  • 7
  • 17
-2

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);
}
Iram Bukhari
  • 487
  • 1
  • 5
  • 15