简体   繁体   中英

How to synchronously query data from room database?

This is my first time doing android dev. Sorry for my lack of knowledge in..well everything.

I am trying to query some data on the main thread of an activity using asynctask. The problem is, the data that I queried is needed immediately in some other query of data, so the asynchronous nature of the query means that every time I need to use the data, the thread has not queried it yet and gives a nullpointer exception. Is there a way to synchronously query data from room database?

I tried the getValue() function from a LiveData object, but it always returns null as well. I am sure that the data is inserted properly within the database, I have checked multiple times looking into the database while debugging.

This is the code I used to query an entity of Day class:

 //load current day
        findSpecificDayAsyncTask asyncTask = (findSpecificDayAsyncTask) new findSpecificDayAsyncTask(mDayDao, new findSpecificDayAsyncTask.AsyncResponse() {

            @Override
            public void processFinish(Day output) {
                day1 = output;
            }
}).execute(date);

It works in due time, but I need the data immediately so that I can query some other data:

mBPViewModel = ViewModelProviders.of(this).get(BulletPointViewModel.class);

                         //the day1 class is used here as a parameter
        mBPViewModel.getSpecificDayBulletPoints(day1.day).observe(this, new Observer<List<BulletPoint>>() {
            @Override
            public void onChanged(@Nullable final List<BulletPoint> bulletPoints) {
                // Update the cached copy of the words in the adapter.
                mAdapter.setBulletPoints(bulletPoints);
            }
        });

So is there a way for me to synchronously query data so I don't get a nullpointer exception?

Why not doing like this

    //load current day
    findSpecificDayAsyncTask asyncTask = (findSpecificDayAsyncTask) new 
    findSpecificDayAsyncTask(mDayDao, new findSpecificDayAsyncTask.AsyncResponse() {

        @Override
        public void processFinish(Day output) {
            day1 = output;
            mBPViewModel = ViewModelProviders.of(this).get(BulletPointViewModel.class);
             //the day1 class is used here as a parameter
            mBPViewModel.getSpecificDayBulletPoints(day1.day).observe(this, new Observer<List<BulletPoint>>() {
                @Override
                public void onChanged(@Nullable final List<BulletPoint> bulletPoints) {
                    // Update the cached copy of the words in the adapter.
                    mAdapter.setBulletPoints(bulletPoints);
                }
            });
        }

    }).execute(date);

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