Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if entity from a room database is empty

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.

like image 251
Claude Hangui Avatar asked Mar 09 '18 16:03

Claude Hangui


2 Answers

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.

like image 153
Joakim Danielson Avatar answered Sep 16 '22 12:09

Joakim Danielson


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
   }
like image 43
Momen Ali Avatar answered Sep 20 '22 12:09

Momen Ali