How to get size of Room list in onCreate/ on main thread?

让人想犯罪 __ 提交于 2019-12-06 12:10:40

This is accessing data synchronously from the LiveData:

Log.d("LISTSIZEVM",  String.valueOf(mViewModel.getAll().getValue().size()));

But this data might no have arrived yet.

Try adding this query to your Dao, see google samples:

@Query("SELECT COUNT(column) FROM table")
int getDataCount();

As pointed out by @CommonsWare this cannot be called from the main UI thread because it's a database opearation that will block the UI thread and will throw an error. You can either call this off the main thread, or return a LiveData<Integer> and observe the value, like you did with the list of data.

@Query("SELECT COUNT(column) FROM table")
LiveData<Integer> getDataCount();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!