Reputation: 506
I want save an image in my database with sugar orm. How can I do this?
I have the next code to try to save it:
Entity:
import android.graphics.drawable.Drawable;
import android.media.Image;
import com.orm.SugarRecord;
import com.orm.dsl.NotNull;
import com.orm.dsl.Unique;
public class Exercise extends SugarRecord {
@Unique
protected String name;
@NotNull
protected String description;
protected Drawable image;
protected String video;
public Exercise() {
}
public Exercise(String name, String description, Drawable image, String video) {
this.name = name;
this.description = description;
this.image = image;
this.video = video;
}
/**
* @return String name
*/
public String getName() {
return name;
}
/**
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* @return String description
*/
public String getDescription() {
return description;
}
/**
* @param description
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @return Image image
*/
public Drawable getImage() {
return image;
}
/**
* @param image
*/
public void setImage(Drawable image) {
this.image = image;
}
/**
* @return String video
*/
public String getVideo() {
return video;
}
/**
* @param video
*/
public void setVideo(String video) {
this.video = video;
}
}
And I am trying to save with the next code:
Exercise addExercise = new Exercise("Prueba", "Prueba 2", image.getDrawable(),"");
addExercise.save();
Variable image is an ImageView, and the image I will save is an image which is taken in the gallery:
if(requestCode == SELECT_PHOTO && resultCode == getActivity().RESULT_OK && null != data)
{
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
image.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
When I try to save appear the next error:
Class cannot be read from Sqlite3 database. Please check the type of field image(android.graphics.drawable.Drawable)
Thank you!
Upvotes: 3
Views: 1718
Reputation: 1169
Try like this
Define
protected byte[] image;
in Exercise class and also change the type of the image variable in constructor. Now convert the image into byte array
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,90,90,stream);
Byte[] image_byte=stream.toByteArray();
Actually storing the entire image in DB is bad idea based on read/write efficiency.It is better to store the image in seperate folder and store the path as a string(varchar) in database
Upvotes: 6