观察没有触发LiveData的房间DAO

时间:2018-04-10 23:15:41

标签: android android-room android-syncadapter android-livedata

尝试使用Room格式化LiveData:

拥有实体对象:

@Entity
public class TimeEntry{
....

DAO:

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

活动内部:

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
...

SyncAdapter内部:

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

我希望在我的活动中,因为我正在观察tDAO.getAll(),它会在同步完成时刷新日历。现在,您必须重新加载活动以获取执行同步后放入数据库的数据。我是Room和LiveData的新手。有任何想法吗?希望我没有拿出太多的代码,这是来自一个相当大的应用程序到目前为止。

1 个答案:

答案 0 :(得分:0)

我最终使用SyncObserver而不是实时数据,因为SyncAdapter确实是我应该监控的。以下是一些片段:

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

后来:

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
            }
         }
}