简体   繁体   中英

Android Room notNull field is expecting a null default value

i'm trying to add new attributes to my tables as shown here:


@Entity(
    tableName = "invoices", indices = [Index(value = [...], unique = true)]
)
data class Invoice(
    ...
    override val created_at: Long = 0,
    override var approved_at: Long? = 0,
) : ICD

so i created the following migration:

val MIGRATION_3_4 = object: Migration(3, 4) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE invoices ADD COLUMN created_at INTEGER NOT NULL DEFAULT 0")
                database.execSQL("ALTER TABLE invoices ADD COLUMN approved_at INTEGER DEFAULT 0 ")
            }
        }

but whenever i try to run it says the migration wasnt handled properly and shows this as expected:

TableInfo{name='invoices', columns={... ,created_at=Column{name='created_at', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='null'}, approved_at=Column{name='approved_at', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0, defaultValue='null'}}, ... }

and this as whats found:

TableInfo{name='invoices', columns={... ,created_at=Column{name='created_at', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0, defaultValue='0'}, approved_at=Column{name='approved_at', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0, defaultValue='0'}}, ... }
        

can anyone tell me why is it expecting default value null please?

What I believe is, you are using Room version greater than 2.2.0 , and version 2.2.0 and above needs default values of the columns to be defined in their respective entity class using @ColumnInfo(defaultValue="0")

For your case add @ColumnInfo(defaultValue="0") to created_at and approved_at

@ColumnInfo(defaultValue="0")
override val created_at: Long = 0,
@ColumnInfo(defaultValue="0")
override var approved_at: Long? = 0,

And change your migration function to this

database.execSQL("ALTER TABLE invoices ADD COLUMN created_at INTEGER NOT NULL DEFAULT 0")
database.execSQL("ALTER TABLE invoices ADD COLUMN approved_at INTEGER")

If you're using a Room version 2.4.0-alpha01 and higher, you can use autoMigration .

For autoMigration , add autoMigrations annotation to your database

@Database(
    entities = [.., .., ..],
    version = 2,
    autoMigrations = [AutoMigration(from = 1, to = 2)]
)
abastract class Database: RoomDatabase

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM