12

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.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Claude Hangui
  • 426
  • 3
  • 8
  • 29

3 Answers3

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
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
  • 3
    LiveData 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
0

Execute a query which return the count of the rows.

Sujin Shrestha
  • 1,203
  • 2
  • 13
  • 23