Check if an Object already exists in Room

Viewed 2835

this might be a stupid question but I cant seem to find the way to see if an object in my database already exists or not. In this case I want to check if the user with everything exists already, check the password with the hashed one and return the Result.

private fun getLoginResult(username: String, password: String): Result<LiveData<BudgetyUser>> {

    try{
        val user = dataSource.getUser(username)
        val passwordDB = user.value?.userPassword
        val saltDB = user.value?.userSalt
        if(user.value == null){
            return Result.ErrorUserNotFound("User $username not found.")
        }
        if (!hashStringSha512(password, saltDB!!).contentEquals(passwordDB!!)) {
            return Result.ErrorWrongPassword("Wrong password.")
        }
        return Result.Success(user)
    } catch (e: SQLiteConstraintException){
        return Result.ErrorUserNotFound("User $username not found.")
    }
    catch (e: Throwable) {
        return Result.LoginException(IOException("Error logging in", e))
    }
}

The dataSource is my DatabasDAO that returns a LiveData Object, but its always null. I try to just get a user by the provided username, and if the returned object is null, no user with that name exists. At least that is the way I wanted it to work. Any Idea how to make it work like that?

Thanks in Advance!

PS. Couldnt find and answer that was what I needed.

interface UserDBDao {

    @Insert
    fun insert(user: BudgetyUser)

    @Update
    fun update(user: BudgetyUser)

    @Query("SELECT * FROM users WHERE user_name = :username")
    fun getUser(username: String) : LiveData<BudgetyUser>


    @Query("DELETE FROM users")
    fun deleteUsers()



}
1 Answers

We don't extract data from a LiveData straight from its value, you should rather observe it. Example:

val userLiveData = dataSource.getUser(username)
userLiveData.observe(this, Observer { user ->
    // Handle user data here
}

Now if you want to find out whether an entry is present on your database you should use COUNT() on your DAO. Example:

@QUERY("SELECT COUNT() FROM BudgetyUser WHERE id = :id")
fun count(id: Int): Int

Then, to find out whether the user you're looking for is in your database, just check if the result of your DAO's count function is greater than 0.

Related