房间数据库迁移 - 位图

问题描述 投票:0回答:2

我正在使用 Room 数据库,我更新了我的模型。这就是我进行迁移的原因,以免删除现有数据。我尝试在迁移时在 SQL 代码中添加位图,但出现错误。如何使用 SQL 代码添加位图?

型号:

@Entity(tableName = "person_table")
data class PersonModel(
    @PrimaryKey(autoGenerate = true)
    val id: Int,
    val name: String,
    val surname: String,
    val profilePicture: Bitmap
)

数据库:

@Database(entities = [PersonModel::class], version = 2, exportSchema = true)
@TypeConverters(Converter::class)
abstract class PersonDatabase : RoomDatabase() {
    abstract fun personDao(): PersonDao

    companion object {

        @Volatile
        private var INSTANCE: PersonDatabase? = null

        fun getDatabase(context: Context): PersonDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    PersonDatabase::class.java,
                    "PersonDatabase"
                ).addMigrations(MIGRATION_1_2)
                    .build()
                INSTANCE = instance
                instance
            }
        }

        val MIGRATION_1_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL(
                    "ALTER TABLE person_table ADD COLUMN profilePicture BITMAP"
                )
            }
        }
    }
}

转换器:

class Converter {

    @TypeConverter
    fun fromBitmap(bitmap: Bitmap): ByteArray {
        val outputStream = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
        return outputStream.toByteArray()
    }

    @TypeConverter
    fun toBitmap(byteArray: ByteArray): Bitmap {
        return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size)
    }

}
android sql kotlin android-room database-migration
2个回答
2
投票

Room 不支持位图,但支持 BLOB 类型,所以你可以这样使用

@ColumnInfo(typeAffinity = ColumnInfo.BLOB)
val profilePicture: ByteArray? = null

并添加扩展以将位图转换为字节数组

fun Bitmap.toByteArray(quality: Int = 50): ByteArray {
    val stream = ByteArrayOutputStream()
    compress(Bitmap.CompressFormat.JPEG, quality, stream)
    return stream.toByteArray()
}

0
投票

正如@Александр提到的,Room不支持位图,但支持BLOB类型。 据此,您提供的解决方案有两个错误:

val MIGRATION_1_2 = object : Migration(1, 2) {
    override fun migrate(database: SupportSQLiteDatabase) {
        database.execSQL(
            "ALTER TABLE person_table ADD COLUMN profilePicture BLOB"
        )
    }
}

所以,应该是

BLOB
而不是
BITMAP
,那么:

@Entity(tableName = "person_table")
data class PersonModel(
    @PrimaryKey(autoGenerate = true)
    val id: Int,
    val name: String,
    val surname: String,
    @ColumnInfo(typeAffinity = ColumnInfo.BLOB)
    val profilePicture: Bitmap
)

它仍然可以是

Bitmap
,但您应该添加
typeAffinity
保留您的转换器

而且,@Александр 的解决方案也有效:)

© www.soinside.com 2019 - 2024. All rights reserved.