I am trying to use RoomDatabase
in my Android App. And I am using LiveData
to be able to refresh my changes automatically inside my fragment.
The first time I am running my app I am getting the data from the API, creating my RoomDatabase
and storing my data.
The second time I run my app I want to check if my DataBase is not empty. But while using LiveData
: the following code is returning null.
AppDatabase.getInstance(getContext()).getRecipeDao().getAllRecipes().getValue();
I have read that "if the response is an observable data type, such as Flowable or LiveData, Room watches all tables referenced in the query for invalidation".
How to check if my RoomDatabase has data or is empty?
So after implementing myself I found that you need to do a few things:
Observer
for changes to the LiveData
observeForever(Observer<T> observer)
unless you are using a LiveCyclerOwner
then use that instead with: observe (LifecycleOwner owner, Observer<T> observer)
getValue()
: Returns the current value. Note that calling this method on a background thread does not guarantee that the latest value set will be received
So to reiterate, I think your approach does not work.
You will need to create some type of separate check rather than use a method that returns a LiveData
class as noted since it does not guarantee the latest value set is received by calling getValue()
.
I would recommend something super simple in the end such as adding a new method to your Dao
@Query("SELECT * FROM recipes LIMIT 1")
Recipe getAnyRecipe();
and do this check looking for null
to see if anything exists in the recipes table.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With