google-developer-training / basic-android-kotlin-compose-training-inventory-app

Apache License 2.0
77 stars 84 forks source link

Persist data with Room Step 7 - Missing fallbackToDestructiveMigration() #55

Open steventran619 opened 1 year ago

steventran619 commented 1 year ago

URL of codelab: https://developer.android.com/codelabs/basic-android-kotlin-compose-persisting-data-room#6

Specify the language of the codelab if it is not English: English

In which task and step of the codelab can this issue be found? Persist Data with Room - Step 7 Last code snippet within Step 20's "final code"

Describe the problem Step 17 mentions adding .fallbackToDestructiveMigration() to the database builder, however that is missing in the final code snippet at the bottom of the page.

CURRENTLY IS:

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase

/**
* Database class with a singleton Instance object.
*/
@Database(entities = [Item::class], version = 1, exportSchema = false)
abstract class InventoryDatabase : RoomDatabase() {

    abstract fun itemDao(): ItemDao

    companion object {
        @Volatile
        private var Instance: InventoryDatabase? = null

        fun getDatabase(context: Context): InventoryDatabase {
            // if the Instance is not null, return it, otherwise create a new database instance.
            return Instance ?: synchronized(this) {
                Room.databaseBuilder(context, InventoryDatabase::class.java, "item_database")
                    .build()
                    .also { Instance = it }
            }
        }
    }
}

SHOULD BE:

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase

/**
* Database class with a singleton Instance object.
*/
@Database(entities = [Item::class], version = 1, exportSchema = false)
abstract class InventoryDatabase : RoomDatabase() {

    abstract fun itemDao(): ItemDao

    companion object {
        @Volatile
        private var Instance: InventoryDatabase? = null

        fun getDatabase(context: Context): InventoryDatabase {
            // if the Instance is not null, return it, otherwise create a new database instance.
            return Instance ?: synchronized(this) {
                Room.databaseBuilder(context, InventoryDatabase::class.java, "item_database")
                    .fallbackToDestructiveMigration()
                    .build()
                    .also { Instance = it }
            }
        }
    }
}

Steps to reproduce? N/A

Versions N/A

Additional information N/A