Saman Sattari
Saman Sattari

Reputation: 3568

Android Room query limit optional

I have a method for getting my data from table:

@Query("SELECT * FROM user LIMIT :limit")
suspend fun getUsers(limit: Int?): List<User>

Now I want this behavior:
If I pass 10 for limit I want getUser method return 10 users
If I pass null for limit I want getUser method return all users.

Is there any solution for this?

Upvotes: 0

Views: 768

Answers (3)

Saman Sattari
Saman Sattari

Reputation: 3568

Now that I'm trying the function:

@Query("SELECT * FROM user LIMIT :limit")
suspend fun getUsers(limit: Int?): List<User>

It is working just the way I want with null parameter. I don't know why it was not working before.

Upvotes: 0

MikeT
MikeT

Reputation: 56938

If I pass null for limit I want getUser method return all users.

If you convert the null into -1 then LIMIT will select all rows. So you cold have:-

@Query("SELECT * FROM user LIMIT :limit")
suspend fun getUsers(limit: Int): List<User>
  • i.e. no need to accept a null, just pass -1 instead of null.

Upvotes: 1

Mohamed Rejeb
Mohamed Rejeb

Reputation: 2629

You can add a new getUsers function that doesn't take any parameter and return all users so your code should look like this.

@Query("SELECT * FROM user LIMIT :limit")
suspend fun getUsers(limit: Int): List<User> // return users with limit number

@Query("SELECT * FROM user")
suspend fun getUsers(): List<User> // return all users

Now you can get all the users by calling getUsers()

Upvotes: 2

Related Questions