Home > Enterprise >  Android Room query limit optional
Android Room query limit optional

Time:07-07

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?

CodePudding user response:

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()

CodePudding user response:

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.
  • Related