Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a single row query with Android Room

Tags:

How do I make a single row query with Android Room with RxJava? I am able to query for List of items, no issues. Here, I want to find if a specific row exists. According to the docs, looks like I can return Single and check for EmptyResultSetException exception if no row exists.

I can have something like:

@Query("SELECT * FROM Users WHERE userId = :id LIMIT 1")
Single<User> findByUserId(String userId);

How do I use this call? Looks like there is some onError / onSuccess but cannot find those methods on Single<>.

usersDao.findByUserId("xxx").???

Any working example will be great!

like image 929
rysv Avatar asked Apr 13 '18 22:04

rysv


People also ask

What is Dao in room?

android.arch.persistence.room.Dao. Marks the class as a Data Access Object. Data Access Objects are the main classes where you define your database interactions. They can include a variety of query methods. The class marked with @Dao should either be an interface or an abstract class.

How do you read a room database?

Database Inspector Officially Support in Android Studio You have to choose your connected device, then need to choose package name that you want to inspect for database. In the left side, show the available tables and need to double click to see table details, and it will be show in the right side.

Is android room an ORM?

Is Android Room an ORM? Room isn't an ORM; instead, it is a whole library that allows us to create and manipulate SQLite databases more easily. By using annotations, we can define our databases, tables, and operations.


1 Answers

According to the docs, looks like I can return Single and check for EmptyResultSetException exception if no row exists.

Or, just return User, if you are handling your background threading by some other means.

@Query("SELECT * FROM Users WHERE userId = :id")
User findByUserId(String id);

How do I use this call?

usersDao.findByUserId("xxx")
  .subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(user -> { ... }, error -> { ... });

Here, I show subscribe() taking two lambda expressions, for the User and the error. You could use two Consumer objects instead. I also assume that you have rxandroid as a dependency, for AndroidSchedulers.mainThread(), and that you want the User delivered to you on that thread.

IOW, you use this the same way as you use any other Single from RxJava. The details will vary based on your needs.

like image 70
CommonsWare Avatar answered Oct 08 '22 16:10

CommonsWare