CodexBloom - Programming Q&A Platform

implementing Room Database Migration Causing NullPointerException in Android 14

👀 Views: 13 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-04
android room migration kotlin

I'm working on a project and hit a roadblock. I'm maintaining legacy code that I'm relatively new to this, so bear with me... I'm experiencing a `NullPointerException` when performing a database migration using Room in my Android app targeting API level 34 (Android 14). I've defined a migration from version 1 to version 2, where I added a new column to an existing table. However, when I try to access the database after the migration, I get the following behavior: ``` java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference ``` Here's the migration code I implemented: ```kotlin val MIGRATION_1_2 = object : Migration(1, 2) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE users ADD COLUMN age INTEGER DEFAULT 0") } } ``` I've also updated the `User` entity to reflect this new column: ```kotlin @Entity(tableName = "users") data class User( @PrimaryKey(autoGenerate = true) val id: Long = 0, val name: String, val age: Int? = null ) ``` In my `RoomDatabase` setup, I have: ```kotlin val db = Room.databaseBuilder( context, AppDatabase::class.java, "app_database" ) .addMigrations(MIGRATION_1_2) .build() ``` To troubleshoot, I checked the database schema using `sqldelight` and confirmed that the new column is present, but I'm still getting the `NullPointerException`. I've also ensured that I'm not trying to access the `age` value directly without checking for null, yet the scenario continues. Any insights on what might be going wrong during the migration process would be highly appreciated. Any ideas what could be causing this? I'm working on a service that needs to handle this. I'm working on a mobile app that needs to handle this. How would you solve this? Cheers for any assistance! This is my first time working with Kotlin latest. Is there a better approach?