Reputation: 685
I have a project requirement like want to store multiple images in room database. so from server side I'm getting image URL so when I'm downloading a image that time only I want to store image in room database and I have total 25 images. After saving images into db, in other fragment want to show these all images for swiping left or right feature.
And for those 25 images, I have one unique id, different name for each image.
First time I'm integrating room database so how can I achieve it? I have gone through many SO answers but didn't get proper idea.
Please guide me. Any help is appreciated.
Upvotes: 1
Views: 2712
Reputation: 991
I Have tried to store images in the room database as Vaibhav said. but you will definitely get an Room curser error like this soon or later
Couldn't read row 0, col 1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
In android Must Store images in scoped storage so no need to get any permission and save that image's path in Room database. glide will make your work easy.
Upvotes: 0
Reputation: 1972
You can use this approach if you don't want to deal with Permssions because if user rejects the Permissions, you can't save the images to file folders.
You can't directly save the Image Bitmap in Room Database but you can store it by converting Bitmap to ByteArray and you can use Type Converted Annotation provided by Room Database by using which you can pass the Object in the Format you want but Room Database will store it in the type which it accepts. To create Type Converter, you have to create a new Class Like this,
class Converters {
@TypeConverter
fun fromBitmap(bmp: Bitmap): ByteArray{
val outputStream = ByteArrayOutputStream()
bmp.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
return outputStream.toByteArray()
}
@TypeConverter
fun toBitmap(bytes: ByteArray): Bitmap {
return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
}
}
And then add @TypeConverters annotation on Top of Room Database Class ,
@Database(entities = [Entity::class],version = 1 , exportSchema = false)
@TypeConverters(Converters::class)
abstract class Database : RoomDatabase() {
abstract fun getDao(): Dao
}
And Entity class be like,
@Entity(tableName = "running_table")
data class Entity(
var img: Bitmap? = null
)
Now you will pass Bitmap to Entity and then Room Database will convert it to ByteArray and will store it and whenever you want to retrieve the database, you will get Bitmap.
Upvotes: 2
Reputation: 448
It is not recommend to store files in SQLite. As you know room works base on SQLite. In your case what i think is to save images in internal storage (It's better to save in file folder because cache folder will be format when ever device storage full) and then save file's name or address in database column and every time you need images you can read address from db and then what ever you want.
Upvotes: 1