简体   繁体   中英

Observing Room DAO with LiveData not being triggered

Trying to make LiveData work with Room:

Have Entity object:

@Entity
public class TimeEntry{
....

DAO:

@Dao
public interface TimeEntryDAO {
    @Query("SELECT * FROM " + TimeEntry.TIME_TABLE_NAME)
    LiveData<List<TimeEntry>> getAll();
...

Inside of Activity:

protected void onCreate(Bundle savedInstanceState) {
...
        AppDatabase db = AppDatabase.getInstance(mContext);
        db = AppDatabase.getInstance(getApplicationContext());
        tDAO = db.timeEntryDao();
        tDAO.getAll().observe(this, new Observer<List<TimeEntry>>() {
            @Override
            public void onChanged(@Nullable List<TimeEntry> mTimeEntries) {
                if (mTimeEntries != null) {
                    loadSelectedDates(mTimeEntries); //updates a calendarUI
                }
            }
        });
        requestImmediateTimeSync(SyncAdapter.GET_USER_TIMES); //Calls syncAdapter
...

Inside of SyncAdapter:

public void onPerformSync(....
...
    AppDatabase db = AppDatabase.getInstance(mContext);
    TimeEntryDAO tDAO;
    tDAO = db.timeEntryDao();
...
    tDAO.insertAll(new TimeEntry(...))
    ...

I was hoping that inside my activity, since I am observing to the tDAO.getAll(), that it would refresh the calendar when the sync is done. Right now, you have to reload the activity to get the data that was put into the database after the sync is performed. I'm new to Room and LiveData. Any ideas? Hopefully I did not take out too much code, this is from a fairly large app so far.

I ended up using a SyncObserver instead of the live data since the SyncAdapter is really what I should be monitoring. Here are some snippets:

    ContentResolver.requestSync(MainActivity.mAccount, getApplicationContext().getResources().getString(R.string.authority), bundle);
...
    final int mask = ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE;
    mSyncObserverHandle = ContentResolver.addStatusChangeListener(mask, mSyncStatusObserver);

Later on:

private SyncStatusObserver mSyncStatusObserver = new SyncStatusObserver() {
        @Override
        public void onStatusChanged(final int which) {
        //Check to see if DAO has anything here, if so, run this thread
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //Do the update thing
            }
         }
}

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