Android LiveData列表未更新 [英] Android LiveData List not updating

查看:321
本文介绍了Android LiveData列表未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Android LiveData和Room Database更新列表.

I am using Android LiveData and Room Database to update a list.

我有一个笔记列表,上面有一个勾号,将它们标记为完成".

I have a list of notes which have a tick to mark them as "DONE".

如果将它们标记为完成,则将它们从当前列表中删除(而不是从数据库中删除),以便它们可以显示在另一页上.

If they are marked done, I remove them from current list (not from database) so that they can be shown on another page.

但是将它们标记为完成不会更新我的列表.

But marking them done does not update my list.

DAO:

    @Dao
public interface NoteDao {
    @Query("SELECT * FROM notes WHERE isDone=0")
    LiveData<List<Note>> getAll();

    @Insert
    void insert(Note note);

    @Delete
    void delete(Note note);

    @Update
    void update(Note note);

}

我的适配器中有一个经过检查的监听器,可以处理列表点击.

I have a onchecked listener in my adapter which handles the list clicks.

 Note note = allNotes.get(position);
 holder.mCheckBox.setListener(isChecked -> {
             note.setIsDone(1);
             mNoteDao.update(note);
             notifyDataSetChanged();
        });

我已经启用了观察功能.

I have put an observe function in activity.

mNoteDao.getAll().observe(this, notes -> {
            if (notes != null && notes.size() > 0) {
                img_no_notes.setVisibility(View.GONE);
                txt_no_notes.setVisibility(View.GONE);
                Collections.reverse(notes);
                mAdapter.setItems(notes);
            } else {
                img_no_notes.setVisibility(View.VISIBLE);
                txt_no_notes.setVisibility(View.VISIBLE);
            }
        });

该列表会在重新启动后更新. 感谢您的帮助.

The list is updated on relaunch. Thanks for your help.

推荐答案

您的LiveData仅负责对Room数据库更改做出反应.如果要更改列表,则需要创建单独的列表或实时数据副本.总体而言,这是一种不好的做法,LiveData + Room仅用于数据库更改,而不用于内存实例.想象一下您的LiveData对象就像包装Room数据库一样.

Your LiveData is responsible for reacting to Room database change only. If you want to change the list you need to create separate list or live data copy. Overall it is bad practice and LiveData+Room is used only for database change not memory instance. Imagine your LiveData object like a wrap over Room database.

这篇关于Android LiveData列表未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆