简体   繁体   中英

Android Room - SELECT query using LiveData

I cannot get the ID of my row using the category and date column. Whenever I use the LiveData observe method to update my int id , the observe method is carried out last.

Eg code:

if(duplicate) {
    Log.e("FIRST: ", "ID: " + id);
    mViewModel.getId(category, date).observe(getActivity(), new Observer<Integer>() {
        @Override
        public void onChanged(@Nullable Integer integer) {
        id = integer;
        Log.e("SECOND", "ID " + id);
        }
    });
    Log.e("THIRD: ", "ID: " + id);
}
Log.v("LOG: ", "ID: " + id);

And this are the results from Logcat:

FIRST: ID: 0

THIRD: ID: 0

LOG:: ID: 0

SECOND: ID 1

Why does the code in mViewModel.getId(category, date).observe... get carried out after Log.v ? And how do I make the id in THIRD and LOG to be set as the same as SECOND (aka 1)?

My code in my ViewModel:

LiveData<Integer> getId(String cat, String date) {return mRepository.getId(cat, date); }

My code in my repository:

LiveData<Integer> getId(String cat, String date) {return mBudgetDao.getId(cat, date); }

My code in my Dao:

@Query("SELECT id FROM budget_table WHERE category = :category AND date = :date")
LiveData<Integer> getId(String category, String date);

Is there any other methods to get ID using query, without using allowMainThreadQueries() in my database?

When you observe the LiveData object in your mViewModel it doesn't mean the onChanged is going to return straight away. If the LiveData object already had a value then you may get it straight away but it's not guaranteed.

What you are essentially doing is observing changes which could happen at any point. In your case, it's a database request that takes some time to complete before returning the value.

LiveData works asynchronously. If you want synchronous results (executed sequentially) you can't use LiveData. You can use allowMainThreadQueries() when building database like

Room.databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME).allowMainThreadQueries().build()

But this is not recommended at all. The process of selecting data will block the main thread. You should give some time to read the LiveData documentations and how asynchronous works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM