如何在android中获取Room数据库的行数? [英] How to get the row count of Room database in android?

查看:271
本文介绍了如何在android中获取Room数据库的行数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遵循拥有 Repository 和 Dao 等的做法.我试图通过一个函数来获取我的数据库存储库中的行数

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();
    }
}

但是 lst 总是计算为 null.我想这与我不被允许从 UI 线程查询数据库有关吗?我应该像实现添加或删除元素一样实现它吗?换句话说,在 Dao 中有一个通过数据库存储库中的 AsyncTask 调用的函数?我对如何做这件非常简单的事情感到困惑.

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.

this 答案显示了在 Dao 中写什么来找出行数,但它没有解释存储库应该如何调用它.

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.

推荐答案

我最终这样做了(使用新线程进行查询).

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

道中

@Query("SELECT COUNT(id) FROM table WHERE is_checked = 1")
int getCount();

在存储库中

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

我需要的地方

    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()

这篇关于如何在android中获取Room数据库的行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆