Search code examples
androidkotlinandroid-studioandroid-roomdatabase-migration

Pre-packaged database has an invalid schema in Room Android kotlin


I am trying to get data from the asset folder SQL DB but I'm getting the following error:

java.lang.IllegalStateException: Pre-packaged database has an invalid schema: recipetype(com.example.finddishrecipe.room.RecipeEntity).
Expected:
TableInfo{name='recipetype', columns={name=Column{name='name', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0, defaultValue='undefined'}, image=Column{name='image', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0, defaultValue='undefined'}, id=Column{name='id', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=1, defaultValue='undefined'}}, foreignKeys=[], indices=[]}
Found:
TableInfo{name='recipetype', columns={id=Column{name='id', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=1, defaultValue='undefined'}, name=Column{name='name', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='undefined'}, image=Column{name='image', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0, defaultValue='undefined'}}, foreignKeys=[], indices=[]}

This is my entity code:

@Entity(tableName = "recipetype")

data class RecipeEntity(
    @PrimaryKey

    @ColumnInfo(name = "id")
    val id: Int,

    @ColumnInfo(name = "name")
    val name: String,

    @ColumnInfo(name = "image")
    val image: String
)

Solution

  • All the columns are supposed to have non null constraints according to expected schema. Define them as non null values while creating the table by adding NOT NULL constraint as follows:

    CREATE TABLE "recipetype" ( "id" INTEGER NOT NULL, "name" TEXT NOT NULL, "image" TEXT NOT NULL, PRIMARY KEY("id" AUTOINCREMENT) )
    

    Or you can make entity class columns as nullables.

    Order of the columns shouldn't matter.