Android架构组件:如何观察数据库中的单个更改

时间:2017-06-19 05:14:43

标签: java android sqlite android-room android-architecture-components

我有几个问题,请看下面的问题:

守则

DAO

@Dao
    public interface PostDao {
        @Query("SELECT * FROM posts ORDER by time DESC")
        LiveData<List<StoryPost>> getAll();

        @Query("SELECT * FROM posts WHERE id = :id")
        LiveData<List<StoryPost>> getPost(String id);

        @Insert(onConflict = OnConflictStrategy.REPLACE)
        @NonNull
        void insert(StoryPost... posts);

        @Delete
        void delete(StoryPost post);

        @Update
        void update(StoryPost post);
    }

Db的

@Database(entities = {StoryPost.class}, version = 5)
    @TypeConverters(Conveter.class)
    public static abstract class AppDatabase extends RoomDatabase {
        private static AppDatabase INSTANCE;

        static AppDatabase getDatabase(Context context) {
            if (INSTANCE == null) {
                INSTANCE = db(context);
            }
            return INSTANCE;
        }

        public abstract PostDao postDAO();
    }

模型视图

public static class PostsViewModel extends AndroidViewModel {
        private final mLiveData data;

        public PostsViewModel(Application application) {
            super(application);
            data = new mLiveData(application);
        }

        public LiveData<List<StoryPost>> getData() {
            return data;
        }

        public void delete(StoryPost post) {
            AsyncTask.execute(() -> db(getApplication()).postDAO().delete(post));
        }
    }

实体(Kotlin)

@IgnoreExtraProperties
@Entity(tableName = "posts")
class StoryPost : Serializable {
    @PrimaryKey
    var id: String? = null
    var time: Long = 0

    var story: StoryPojo? = null

    @Embedded
    var user: User? = null

    constructor() {

    }
}

LiveData

public static class mLiveData extends LiveData<List<StoryPost>> {
        private final Context context;

        public mLiveData(Context context) {
            this.context = context;
            loadData();
        }

        private void loadData() {

        }

        @Override
        protected void onActive() {
        }

        @Override
        protected void onInactive() {
        }
    }

问题1:

使用上面的代码,我的理解是我应该使用viewModel观察数据如下。我想使用ViewModel,但是在“观察”时我没有获得任何数据,我该如何解决这个问题?

PostsViewModel model = ViewModelProviders.of(this).get(PostsViewModel.class);
        model.getData().observe(this, data -> {
            adapter.addList(data);
        });

但是这不会返回任何数据,而以下情况很有效:

LiveData<List<StoryPost>> liveData = postDAO(context).getAll();
            AsyncTask.execute(() -> {
                liveData.observeForever(storyPosts -> postValue(storyPosts));
            });

问题2:

如果我使用这个:

LiveData<List<StoryPost>> liveData = postDAO(context).getAll();
                AsyncTask.execute(() -> {
                    liveData.observeForever(storyPosts -> postValue(storyPosts));
                });

如何观察数据库中的单个更改,例如删除行还是添加新行?

0 个答案:

没有答案