I'm new to Kotlin, I can't manage login form validation. My idea is to compare inputEmail to email existing in Database. If module returns only true
class LoginViewModel(application: Application) : AndroidViewModel(application) {
private val repository: UserRepository
init {
val userDao = AppDatabase.getInstance(application).userDao()
repository = UserRepository(userDao)
}
fun getUserEmail(email: String) {
viewModelScope.launch(Dispatchers.IO) {
repository.getUserEmail(email)
}
}
}
function inside LoginFragment:
private fun logIn() {
val email = binding.editEmailAddress.text.toString()
val password = binding.editPassword.text.toString()
if (inputCheck(email, password)) {
mLoginViewModel = ViewModelProvider(this)[LoginViewModel::class.java]
val emailList = mLoginViewModel.getUserEmail(email)
if (emailList!=null)
Toast.makeText(requireContext(), "Logged in as $email", Toast.LENGTH_LONG).show()
findNavController().navigate(R.id.action_loginFragment_to_listFragment)
} else {
Toast.makeText(requireContext(), "Fill out blank fields", Toast.LENGTH_LONG).show()
}
}
UserDao:
@Dao
interface UserDao { @Insert suspend fun addUserToDatabase(user: User)
@Query("SELECT * FROM user_table ORDER BY userId DESC")
fun getAllUsers(): LiveData<List<User>>
@Query("SELECT * FROM user_table WHERE E_mail LIKE :email")
suspend fun getUserEmail(email: String): User?
}
fun getUserEmail(email: String) {
viewModelScope.launch(Dispatchers.IO) {
repository.getUserEmail(email)
}
}
this method has no return specified in the signature and no actual return statement either, it just does whatever you tell it to do, which means that the result of calling this function is going to be assigning Unit
to emailList
. is Unit
equal to null ? no. that's why your if will always fail. to write a function which returns something, you have to specify a return type in your functions signature, however, because you're making use of async operations, a return type isn't necessarily what you're looking for. Consider having a look at something like liveData or learn more about async operations here