如何在我的 Sugar ORM 数据库中保存图像?

How can I save image in my Sugar ORM database?

我想用 sugar 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));
        }

当我尝试保存时出现下一个错误:

Class cannot be read from Sqlite3 database. Please check the type of field image(android.graphics.drawable.Drawable)

谢谢!

这样试试

定义

protected byte[] image; 

在练习 class 中,并在构造函数中更改图像变量的类型。 现在将图像转换成字节数组

  ByteArrayOutputStream stream=new ByteArrayOutputStream();
   bitmap.compress(Bitmap.CompressFormat.PNG,90,90,stream);
   Byte[] image_byte=stream.toByteArray();

实际上将整个图像存储在数据库中是个坏主意 read/write efficiency.It 最好将图像存储在单独的文件夹中并将路径作为字符串(varchar)存储在数据库中