How can I detect if a table has no entries using Room Persistence Library? I can't find any information on how to tackle this issue.
Asked
Active
Viewed 1.4k times
3 Answers
11
Create a SELECT count(*) FROM ...
query that returns an int or a SELECT * FROM ...
query that returns an array and check the size of the array.

Henry Twist
- 5,666
- 3
- 19
- 44

Joakim Danielson
- 43,251
- 5
- 22
- 52
-
is there any way we could check this more efficiently? – V Surya Kumar May 25 '22 at 18:25
-
More efficiently than what? It’s very hard to give a response to something as vague as "more efficiently" – Joakim Danielson May 25 '22 at 19:43
2
simply you can make a query and check if the result is empty. Like this
this code in Dao
@Query("SELECT * FROM table ORDER BY id LIMIT 1")
LiveData<TaskEntry> loadlastTask();
then in your ViewModel class, you can call this and check
LiveData<TaskEntry> mDBTask;
private AppDataBase mDB;
mDBTask = mDB.taskDao().loadlastTask();
if(mDBTask.getValue() == null ){
//table is empty
}else{
// table is not empty
}

Momen Ali
- 21
- 6
-
3LiveData is asynchronous. There is no guarantee that condition `mDBTask.getValue() == null ` will always be the correct logic because `loadlastTask()` may not complete exactly before the if statement executes. – Koushik Shom Choudhury Apr 15 '20 at 20:39
-
I'm trying to do the same, but since i need this information to remove a piece of UI, i created a function in the viewmodel to call the query in the DAO, and i'm trying to use this function to establish if the UI element must be removed or not in the fragment itself. Is this correct? – m.i.n.a.r. Apr 23 '20 at 13:04