Claude Hangui
Claude Hangui

Reputation: 427

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.

Upvotes: 12

Views: 14506

Answers (3)

Joakim Danielson
Joakim Danielson

Reputation: 51871

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.

Upvotes: 11

Momen Ali
Momen Ali

Reputation: 21

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
   }

Upvotes: 2

Sujin Shrestha
Sujin Shrestha

Reputation: 1253

Execute a query which return the count of the rows.

Upvotes: 0

Related Questions