I am struggling with saving image on sqlite.
I am trying to save image as blob on sqlite.
I don’t know how to declare imageView to byte[] because I am using insert method on dbAdapter.
Is it good way to save the image into database? some people said that saving file path url into database is better. If it is better, please give me some your hands.
I am really getting tough for that.
Many thanks.
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) return;
switch (requestCode)
{
case PICK_FROM_CAMERA:
Bundle extras = data.getExtras();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Bitmap selectedImage = (Bitmap) extras.get("data");
selectedImage = Bitmap.createScaledBitmap(selectedImage, 200, 250, false);
selectedImage.compress(CompressFormat.PNG, 0, bos);
mImageView.setImageBitmap(selectedImage);
break;
case PICK_FROM_GALLERY:
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
mImageView.setImageURI(selectedImageUri);
break;
}
}
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
saveState();
}
private void saveState()
{
String name = (String) nameEdit.getText().toString();
String category = (String) categoryEdit.getText().toString();
String expired_date = (String) expired_Date_Btn.getText().toString();
//byte[] image = (byte[]) mImageView... I HAVE TO DO SOME CODING HERE..
if(mRowId == null)
{
long id = mDbHelper.insertItem(category, name, expired_date, image);
if(id>0)
{
mRowId = id;
}
}
else
{
mDbHelper.updateItem(mRowId, category, name, expired_date, image);
}
}
DbAdapter class
public long insertItem(String category, String name, String expired_date, byte[] image)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_CATEGORY, category);
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_EXPIRED_DATE, expired_date);
initialValues.put(KEY_IMAGE, image);
return db.insert(DATABASE_TABLE, null, initialValues);
}
Try doing this:
With ConvertDrawabelToByteArray defined like this:
Though I think you should be able to get the bytes out of the Bitmap as well. All that said, storing the filepath in sql lite would probably be more efficient, however, if the user deletes the image you’d have to handle that in your application.