【发布时间】:2020-12-08 13:36:08
【问题描述】:
我正在按照 Android Architectural Components 设计编写一个 android 应用程序。
这是数据库类:
@Database(entities = [Authentication::class],version = 1, exportSchema = false)
abstract class AuthDB: RoomDatabase(){
abstract val authenticationDao :AuthenticationAccessObject
companion object{
@Volatile
private var INSTANCE: AuthDB? = null
fun getInstance(context: Context): AuthDB {
synchronized(this){
var instance = INSTANCE
if(instance == null){
instance = Room.databaseBuilder(
context.applicationContext,
AuthDB::class.java,
"authentication_database"
)
.fallbackToDestructiveMigration()
.build()
INSTANCE = instance
}
return instance
}
}
}
}
这是存储库类:
class Repository2() {
private val database: AuthDB = AuthDB.getInstance(context = getContext())
private val daoA = database.authenticationDao
//Function to register a new user to system
fun insertAuth(userData: Any){
if (userData is Authentication){
daoA.insertAuth(userData)
} else {
throw IllegalArgumentException()
}
}
我的目标是,当我编写 ViewModel 时,我想创建 Repository2 的实例并调用函数,例如:
var repo = Repository2()
repo.insertAuth(authenticationObject)
我在为存储库中的 getInstance 提供上下文时遇到问题。上下文应该是这样的,当我实例化存储库时,它应该自动获取应用程序上下文并实例化 AuthDB 数据库。
到目前为止,
-
我尝试创建扩展 Application 的 Application 类,并尝试按照另一个 stackoverflow 解决方案中的建议从那里获取应用程序上下文
-
使用以下代码实例化数据库并失败:
私有验证数据库:AuthDB = AuthDB.getInstance(context = getContext())
-
使用以下代码实例化数据库并失败:
私有验证数据库:AuthDB = AuthDB.getInstance(Application.getApplicationContext())
我已经尝试了大约两天,但没有任何效果,我相信我在这里遗漏了一个主要概念。我希望有人可以将我推向正确的方向?
亲切的问候, 萨利克
【问题讨论】:
标签: android kotlin repository-pattern android-viewmodel