本文介绍了匕首2获得自己的Room实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向会议室数据库添加一个回调以填充初始数据.

I want to add a callback to the room database to populate initial data.

@Provides
@Singleton
fun provideRoom(context: Context): MyRoomDatabase {
    return Room.databaseBuilder(context, MyRoomDatabase::class.java, "my_database")
        .fallbackToDestructiveMigration()
        .addCallback(object : RoomDatabase.Callback() {
            @Override
            override fun onCreate(db: SupportSQLiteDatabase) {
                super.onCreate(db)

            }
        })
        .build()
}

为此,我需要回调中的数据库实例来访问DAO以插入数据.如何运作?

For that i need the database instance in the callback to access DAO for inserting data.How does this work?

我要实现的目标:Create initial data for the room database at the app installation

我的Callback Class:

class RoomCallback(
 var myRoomDatabase : MyRoomDatabase
)  : RoomDatabase.Callback()  {
override fun onCreate(db: SupportSQLiteDatabase) {
    myRoomDatabase.basicItemDao().insertList(
        listOf(
            BasicItem(),
            BasicItem()
        )
    )
}

}

我如何提供RoomDatabaseRoomCallback:

@Provides
@Singleton
fun provideRoom(context: Context, roomCallback: RoomCallback): MyRoomDatabase {
    return Room.databaseBuilder(context, MyRoomDatabase::class.java, "my_database")
        .fallbackToDestructiveMigration()
        .addCallback(roomCallback)
        .build()
}

@Provides
@Singleton
fun provideRoomCallback(myRoomDatabase: MyRoomDatabase): RoomCallback {
    return RoomCallback(myRoomDatabase)
}

问题:-RoomCallbackRoomDatabase实例都需要另一个实例.

PROBLEM:- The RoomCallback and RoomDatabase instance need both the other instance.

推荐答案

首先设置数据库

@Database(
    entities = [User::class],
    version = VERSION_CODE
)
abstract class DatabaseManager : RoomDatabase() {
    abstract fun userDao(): UserDao
}

现在创建一个DatabaseModule

Now create a DatabaseModule

@Module
class DatabaseModule {

    @Singleton
    @Provides
    fun provideRoomDatabase(@ApplicationContext context: Context): RoomDatabase {
        return Room.databaseBuilder(context, RoomDatabase::class.java, "dbName")
            .setJournalMode(JournalMode.TRUNCATE)
            .build()
    }
}

您可以创建一个单独的模块,也可以在DatabaseModule中添加自己提供的dao对象的方法.举例来说,我有一个UserDao然后

You can create a separate module or add a method in DatabaseModule it self providing dao object. Say for example I have a UserDao then

@Module
class UserModule {

    @Singleton
    @Provides
    fun provideDao(database: DatabaseManager): UserDao {
        return database.userDao()
    }
}

这篇关于匕首2获得自己的Room实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 02:33