NiceToMytyuk
NiceToMytyuk

Reputation: 4277

How to get last value from Room using Kotlin?

How should i return only one value from Room?

I've made my query in the DAO like:

@Query("SELECT * FROM testata WHERE id = (SELECT MAX(id) FROM testata)")
fun selectLast(): Testata

Which should return the last insert row, then in my repository i've done the following:

@WorkerThread
suspend fun lastTestata(): Testata {
    return testataDAO.selectLast()
}

And in the ViewModal i was trying the following:

fun lastTestata(): Testata = viewModelScope.launch {
    return repository.lastTestata()
}

But instead it requires Job instead of testata in ViewModal fun lastTestata() so what is the right way to get single values from room in android?

Upvotes: 1

Views: 1801

Answers (2)

Gabriel Muniz
Gabriel Muniz

Reputation: 21

If your id is incremental(should be) you can use the limit to get one register, like this:

SELECT * FROM testata ORDER BY ID DESC LIMIT 1

Upvotes: 2

Divij Gupta
Divij Gupta

Reputation: 175

The query "SELECT * FROM testata WHERE id = (SELECT MAX(id) FROM testata)" will return a list. So you can write something like

@Query("SELECT * FROM testata WHERE id = (SELECT MAX(id) FROM testata)")
fun selectLast(): List<Testata>

And in your repo you can write

@WorkerThread
suspend fun lastTestata(): Testata {
    return testataDAO.selectLast().get(0)
}

Upvotes: 0

Related Questions