Search code examples
androidandroid-room

How to get the row count of Room database in android?


I'm following the practice of having a Repository and a Dao and so on. I was trying to get the row count in my database repository by having a function

int getNumFiles() {
    List<AFile> lst = files.getValue();  // files is of type LiveData<List<AFile>> files;
    if (lst == null) {
        return 0;
    } else {
        return lst.size();
    }
}

But lst always evaluates to null. I guess it has something to do with me not being allowed to query the DB from the UI thread or something? Should I implement it like one implements adding or deleting an element? In other words have a function in the Dao which is called via an AsyncTask in the Database repository? I'm confused about how to do this very simple thing.

There is this answer which shows what one would write in the Dao to find out the number of rows, but it does not explain how the repository should call this.


Solution

  • I ended up doing it like this (using a new thread for the query).

    In the Dao

    @Query("SELECT COUNT(id) FROM table")
    int getCount();
    

    In the repository

    int getNumFiles() {
        return afileDao.getCount();
    }
    

    Where I need it

        final AtomicInteger fcount = new AtomicInteger();
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                int num = f_repo.getNumFiles();
                fcount.set(num);
            }
        });
        t.setPriority(10);
        t.start();
        t.join();
        // use as fcount.get()