【问题标题】:how can i get database instance in another kotlin class based on my main database class我如何根据我的主数据库类在另一个 kotlin 类中获取数据库实例
【发布时间】:2022-12-08 02:42:45
【问题描述】:

在我的项目中,我使用单例设计模式,添加一个伴生对象和一个返回数据库对象实例的函数。这将避免创建多个实例 数据库对象,通过它建立与 SQL 服务器的连接。
我有以下代码连接到数据库:

// Annotates class to be a Room Database with a table (entity) of the Word class
@Database(entities = arrayOf(ShoppingList::class), version = 1, exportSchema = false)
public abstract class ShoppingListRoomDatabase : RoomDatabase() {
    abstract fun shoppingListDao(): ShoppingListDao

    companion object {
        // Singleton prevents multiple instances of database opening at the
        // same time.
        @Volatile
        public var INSTANCE: ShoppingListRoomDatabase? = null

        fun getDatabase(context: Context, scope: CoroutineScope): ShoppingListRoomDatabase {
            // if the INSTANCE is not null, then return it,
            // if it is, then create the database
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    ShoppingListRoomDatabase::class.java,
                    "shopping_list_database"
                ).addCallback(ShoppingListDatabaseCallback(scope)).build()
                INSTANCE = instance
                // return instance
                instance
            }
        }
    }
}

private class ShoppingListDatabaseCallback(
    private val scope: CoroutineScope
) : RoomDatabase.Callback() {
    override fun onCreate(db: SupportSQLiteDatabase) {
        super.onCreate(db)
        ShoppingListRoomDatabase.INSTANCE?.let { database ->
            scope.launch {
                populateDatabase(database.shoppingListDao())
            }
        }
    }
    fun populateDatabase(shoppingListDao: ShoppingListDao) {
        shoppingListDao.deleteAll()
        var shoppingList = ShoppingList(1,"First List")
        shoppingListDao.insert(shoppingList)
        shoppingList = ShoppingList(2, "Second List!")
        shoppingListDao.insert(shoppingList)
    }
}

界面:

@Dao
interface ShoppingListDao {
    @Query("SELECT * FROM shopping_lists ORDER BY id ASC")
    fun getOrderedShoppingLists(): Flow<List<ShoppingList>>
    @Insert
    fun insert(shoppingList: ShoppingList)
    @Query("DELETE FROM shopping_lists")
    fun deleteAll()
}

如何在另一个 kotlin 类中获取此数据库实例以使用它?

【问题讨论】:

    标签: android kotlin


    【解决方案1】:

    好吧,您可以在“其他文件”(类)中创建一个对象并使用它或直接调用该类

    val myDatabase = ShoppingListRoomDatabase()
    myDatabase.getDatabase(this ,* your scope*) 
    

    或直接:

    ShoppingListRoomDatabase().getDatabase(this , *your scope*) 
    

    【讨论】:

    • 我应该放什么而不是*your scope*
    • @np。我建议你简单地删除它,使用这样的范围协程很复杂(至少对我而言),我使用的第二种方法是暂停你的 Dao 函数,然后在协程范围内调用它们(使用它们)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 2015-10-06
    • 2016-08-31
    相关资源
    最近更新 更多