Hi guys, I am creating a database in room and I have had these problems:
*Cannot create an instance of class com.example.votestatistics.data.UserViewModel
*lateinit property readAllData has not been initialized
class UserRepository(private val userDao: UserDao) {
lateinit var loginDatabase: UserDatabase
lateinit var readAllData: LiveData<User>
suspend fun adduser(user: User) {
userDao.addUser(user)
}
fun initializeDB(context: Context): UserDatabase {
return UserDatabase.getDatabase(context)
}
fun getLoginDetails(context: Context, username: String, password: String): LiveData<User>{
loginDatabase = initializeDB(context)
readAllData = loginDatabase.userDao().readAllData(username, password)
return readAllData
}
}
///UserViewModel
class UserViewModel(application: Application) : AndroidViewModel(application) {
var readAllData: LiveData<User>
var repository: UserRepository
init {
val userDao = UserDatabase.getDatabase(
application
).userDao()
repository = UserRepository(userDao)
readAllData = repository.readAllData
}
fun addUser(user: User) {
viewModelScope.launch(Dispatchers.IO) {
repository.adduser(user)
}
}
fun getLoginDetails(context: Context, username: String, password: String): LiveData<User>? {
readAllData = repository.getLoginDetails(context, username, password)
return readAllData
}
}
//Fragment
binding.buttonIngresar.setOnClickListener {
val name = binding.textInputUser.editText?.text.toString()
val passWord = binding.textInputPassword.editText?.text.toString()
context?.let { it1 ->
mUserViewModel.getLoginDetails(it1, name, passWord)?.observe(viewLifecycleOwner, Observer {
if (it == null) {
Toast.makeText(context, "No Found", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(context, "Found", Toast.LENGTH_SHORT).show()
}
})
}
}