首页 > 解决方案 > 在 Room db 中查找具有 id 的项目并在 ViewModel 中接收它

问题描述

我有一个应用程序,它代表MainActivity. SecondActivity当用户单击其中一项时,我想去。在SecondActivity注释的内容中应该显示出来。
我需要获取项目的 id 并将其发送到SecondActivity. 我可以用这个查询来做到这一点:

@Query("SELECT id FROM notes WHERE id == :id")
    Note getNote(int id);

但我不知道该怎么做ViewModel。我创建了一个AsyncTask运行 getNote() 方法的扩展类。我必须通过返回这个注释,AsyncTask但是因为这个类没有在我不能使用的 Activity 中创建onPostResult。创建后AsyncTask我必须做什么?

这是我的视图模型:

public class NoteViewModel extends AndroidViewModel {

    private NoteRepository repository;
    private LiveData<List<Note>> allNotes;


    public NoteViewModel(@NonNull Application application) {
        super(application);
        repository = new NoteRepository(application);
        allNotes = repository.getAllNotes();
    }

    LiveData<List<Note>> getAllWords() {
        return allNotes;
    }
    public void insert(Note note) {
        repository.insert(note);
    }
    public void delete(Note note) {
        repository.deleteNote(note);
    }

}

这是注意:

@Entity(tableName = "notes")
public class Note {

    @PrimaryKey(autoGenerate = true)
    public int id;

    private String title;
    private String text;

    public Note(String title, String text) {
        this.title = title;
        this.text = text;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

}

标签: androidandroid-asynctaskviewmodelandroid-room

解决方案


推荐阅读