android - 在 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;
}
}
解决方案
推荐阅读
- django - Django 管理员如何创建自定义视图以重定向到另一个模型添加视图?
- python-3.x - 如何将 mypy 推断循环变量修复为“对象”?
- css - 文本颜色在块内而不是在块外更改
- javascript - 如何扩展默认的 PEG.js 算术示例以允许多个表达式而不是单个表达式?
- html - 使粘性表格标题行完全不透明
- reactjs - 如何测试具有片段的功能组件?
- php - 如何在 Smarty 脚本中将表达式分配给变量并检查它是奇数还是偶数
- python - 如何将 Flask connexion 与 redis 一起使用?
- javascript - 任何气泡地球地图文本颜色变化
- javascript - 我使用我制作的网站制作了一个 webview 应用程序,但奇怪的是,该应用程序的某些部分不起作用