Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use createFromAsset function from Room library?

Room persistence library version 2.2.0-alpha01 has added the ability to use pre-packaged databases.

https://developer.android.com/jetpack/androidx/releases/room

Can someone provide an example for how to initialize the room database builder?

like image 245
syloc Avatar asked Dec 19 '25 03:12

syloc


1 Answers

I'm using this :

@Database(entities = [Users::class], version = 1, exportSchema = false)
abstract class AppDataBase : RoomDatabase() {

    companion object {
        private const val DATABASE_NAME = "you_name"
        private const val DATABASE_DIR = "database/you_name.db" // Asset/database/you_name.db

        fun getInstance(context: Context): AppDataBase {
            return Room
                    .databaseBuilder(context, AppDataBase::class.java, DATABASE_NAME)
                    .createFromAsset(DATABASE_DIR)
                    .build()
        }
    }

    abstract fun getUsers(): UsersDao
}

for more information refer here

If you need update DB from Asset!
 1. You need level up version Database in settings Room!
 2. Add .fallbackToDestructiveMigration() method in getInstance
 3. And need level up version in you db file;
like image 179
Evgen But Avatar answered Dec 21 '25 17:12

Evgen But



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!