How to save images to Room Persistence Library

你说的曾经没有我的故事 提交于 2019-12-10 22:51:12

问题


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."


回答1:


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.




回答2:


you can not store pure image, have many options to store image:

  1. convert image to base64 and store in database
  2. save in local storage and store Uri in database
  3. get image URL from server and store URL in database


来源:https://stackoverflow.com/questions/57117262/how-to-save-images-to-room-persistence-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!