Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save images to Room Persistence Library

Originally I was adding information (Strings) and a photo (from drawable) to card views. I had it working from a list and adding it to the cards within a recycler view using an adapter and such. Now I'm trying to migrate to saving this information using the Room Persistence Library and instead of adding dummy info in the code I am going to make it come from user input, as I'm trying to implement this I have discovered that saving images to Room DB is not too easy. The strings are working fine now I just need a way to save the images after taken from the camera.

I can't store images in the Room DB using types Image, Bitmap, URI, Drawables.

@Entity(tableName = "machines_table")
public class Machines {


    @PrimaryKey(autoGenerate = true)
    private int id;
    private Drawable photoId;
    private String name;
    private String location;

    public Machines(String name, String location, Drawable photoId) {
        this.name = name;
        this.location = location;
        this.photoId = photoId;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public String getLocation() {
        return location;
    }

    public Drawable getPhotoId() {
        return photoId;
    }

}

I guess I expected to be able to save images more easily however this is not the case when using any of the types I listed above I am given this error.

"error: Cannot figure out how to save this field into database. You can consider adding a type converter for it."

like image 535
Raymond Riter Avatar asked Dec 13 '22 11:12

Raymond Riter


1 Answers

You'll probably are able to save them as byte[], however it is generally regarded as unwise to save bitmaps to the DB. Store them to the filesystem and save the filename (a UUID based one for example) to the DB. Then retrieve the file when needed.

The database would become huge and slow if it stores the images themselves.

like image 98
Peterdk Avatar answered Dec 26 '22 19:12

Peterdk