Home > other >  how do i store image in room database
how do i store image in room database

Time:12-21

how do i store image in room database, From Json. as i was trying to store with Byte it gives me error - java.lang.NumberFormatException: For input string: "https://upload.wikimedia.org/wikipedia/commons/4/41/Sunflower_from_Silesia2.jpg"

data Class

@Entity(tableName = "actor",indices = arrayOf(Index(value= arrayOf("id"),unique = true)))
data class ActorItem(
    @PrimaryKey(autoGenerate = true)
    val id_:Int,
    @SerializedName("age")
    @ColumnInfo(name = "age")
    val age: String,
    @SerializedName("id")
    @ColumnInfo(name = "id")
    val id: Int,
    @SerializedName("image")
    @ColumnInfo(name="image")
    val image: Byte,
    @SerializedName("name")
    @ColumnInfo(name = "name")
    val name: String
)

here is Json

[
 {"id": 1,
  "name": "Hero",
  "image": "https://upload.wikimedia.org/wikipedia/commons/4/41/Sunflower_from_Silesia2.jpg",
  "age": "23"}
]

CodePudding user response:

Are you trying to store the path to an image in the DB, or the image itself?

If the path, then image would be of type String (not Byte). Storing a path (or name) in the DB, and not the image contents, is generally considered best practice. It requires downloading and saving the image in the filesystem outside of the DB.

If you are trying to store the image contents in the DB though, then the field type would be ByteArray (not Byte), the column type would be Blob, and you will need to download the image and write the bytes in to the DB yourself.

Related:

CodePudding user response:

Simple solution is to store image file in internal directory(App-specific storage) and store the internal private path in your room database column.

Internal App storage Docs :- https://developer.android.com/training/data-storage/app-specific

Or make base64 of file image file and store base64 string in your database column

  • Related