我想用糖orm在我的数据库中保存图像。我怎么能这样做?
我有下一个代码试图保存它:
实体:
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;
}
}
我正试着用下一个代码保存:
Exercise addExercise = new Exercise("Prueba", "Prueba 2", image.getDrawable(),"");
addExercise.save();
变量图像是一个ImageView,我将保存的图像是在图库中拍摄的图像:
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));
}
当我尝试保存时出现下一个错误:
无法从Sqlite3数据库中读取类。请检查类型 field image(android.graphics.drawable.Drawable)
谢谢!
答案 0 :(得分:6)
试试这个
定义
protected byte[] image;
在Exercise类中,也可以在构造函数中更改图像变量的类型。 现在将图像转换为字节数组
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,90,90,stream);
Byte[] image_byte=stream.toByteArray();
实际上将整个图像存储在DB中是基于读/写效率的坏主意。最好将图像存储在单独的文件夹中并将路径存储为数据库中的字符串(varchar)