Convert Database Entity from Java to Kotlin

Viewed 268

I am currently converting my projects to Kotlin and I have an app with Room database using Java.

My Entity in Java

@Entity(tableName = "store")
@Fts4
public class Store {

    @PrimaryKey
    @ColumnInfo(name = "rowid")
    private Long identification;

    @NonNull
    @ColumnInfo(name = "name")
    private String name;

    @ColumnInfo(name = "location")
    private String location;

    @ColumnInfo(name = "days_open")
    private int daysOpen;

    public Store(Long identification, @NonNull String name, String location, int daysOpen) {
        this.identification = identification;
        this.name = name;
        this.location = location;
        this.daysOpen = daysOpen
    }

    public Long getIdentification() {
        return identification;
    }

    @NonNull
    public String getName() {
        return name;
    }

    public String getLocation() {
        return location;
    }

    public int getDaysOpen() {
        return daysOpen;
    }
}

I convert it this way to Kotlin

@Entity(tableName = "store")
@Fts4
data class Store(

    @PrimaryKey @ColumnInfo(name = "rowid") 
    val identification: Long?,

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

    @ColumnInfo(name = "location")
    val location: String?

    @ColumnInfo(name = "days_open")
    val daysOpen: Int?
)

Now I am having this error

java.lang.IllegalStateException: Room cannot verify the data integrity. Looks like you've changed schema but forgot to update the version number. You can simply fix this by increasing the version number.
 

Do we really need to do migration in this? Or I am wrong converting things. I am using Room 2.3.0.

implementation "androidx.room:room-ktx:2.3.0"
kapt "androidx.room:room-compiler:2.3.0"

When I updated the database version, this is the error

java.lang.IllegalStateException: A migration from 1 to 2 was required but not found. Please provide the necessary Migration path via RoomDatabase.Builder.addMigration(Migration ...) or allow for destructive migrations via one of the RoomDatabase.Builder.fallbackToDestructiveMigration* methods.
   

I added this code to my database

val MIGRATION_1_2 = object : Migration(1, 2) {
    override fun migrate(database: SupportSQLiteDatabase) {
        database.execSQL("
        // put changes here
        ")}
}

I don't know what to put inside of migrate function. Any idea?

2 Answers

Exception message seems to be quite clear. you need to update the version of your room database. Go to the class that extends RoomDatabase and increment the value of version attribute in @Database annotation.

@Database(entities = [A::class, B::class], version = 2)
abstract class YourRoomDatabase: RoomDatabase() 

Already got the solution.

The problem is my int in Java Entity is different w/ Int in Kotlin. Thus, I need to update my schema by Migration. My solution is referenced here.

Related