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

2019-06-06 07:27发布

问题:

How can I easily get the count of the database size so I can then do the appropriate actions based on whether the DB is empty or not?

I have an App DB, View Model, Repository, Dao, and all the other pieces, and my objects insert... But I cannot call in onCreate() the size of the list in the DB. When I ever try to get mAppDatabase.vehicleDao().getAll().getValue().size(), or mVehicleViewModel.getAll().getValue().size(), I get null pointer exceptions.

However I know my objects are inserting because when I run an observable, I can log their information... but I cannot get the count on the main thread/ in onCreate. Help! Example code below:

protected void onCreate(Bundle savedInstanceState) {
...
mAppDatabase = AppDatabase.getInstance(MyActivity.this);
Log.d("LISTSIZEAPP", String.valueOf(mAppDatabase.myDao().getAll().getValue().size()));
ObserveItems();

OR

protected void onCreate(Bundle savedInstanceState) {
...
mViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
Log.d("LISTSIZEVM",  String.valueOf(mViewModel.getAll().getValue().size()));
ObserveItems();

^Null pointer exception for both (Attempt to invoke interface method 'java.lang.Object[] java.util.List.toArray()' on a null object reference)...

however:

private void ObserveItems() {
    mViewModel.getAll().observe(this, new Observer<List<Foo>>() {
        @Override
        public void onChanged(@Nullable final List<Foo> foos) {
            mFoos= foos;
            for (Vehicle v: mFoos) {
                Log.d("ROOM INFO - FOOS", v.getFooTitle());
            }
        }
    });
}

I can log all the info I want. So the items are CLEARLY inserted. What gives? What am I missing? Thank you.

回答1:

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