我有一个无法解决的大问题。我正在开发一个“提醒应用程序”,它允许您插入备忘录并在需要执行此操作时通知您。好吧,我在 Android 中使用 Room,当我插入新任务时,我想使用插入任务的 id 作为管理通知的 id。我有 TaskViewModel 和 TaskRepository。这是我写的代码:
在 DAO 中我有:
@Insert
long insert(Task task);
在主要 Activity 中我有:
Task task = new Task(title, data_calendario, time, priority, type, note, "pending");
taskViewModel.insert(task);
在 TaskViewModel 中我有:
public void insert(Task task){
repository.insert(task);
}
在 TaskRepository 中我有:
public void insert(Task task){
new InsertTaskAsyncTask(taskDao).execute(task);
}
private class InsertTaskAsyncTask extends AsyncTask<Task, Void, Long>{
private TaskDao taskDao;
private InsertTaskAsyncTask(TaskDao taskDao){
this.taskDao = taskDao;
}
@Override
protected Long doInBackground(Task... tasks) {
Long test = taskDao.insert(tasks[0]);
System.out.println("Stampa repository BUONO: "+test); //here I have the id that I need (I think..)
return test;
}
@Override
protected void onPostExecute(Long test) {
super.onPostExecute(test);
id = test;
}
}
我读到可以从 Insert 方法中检索插入行的 id(我的 task_table 上有一个自动生成的 int Id 作为主键),这应该是我所需要的。 现在我的问题是,如何将插入任务的 id 从 TaskRepository 返回到我的 MainActivity 以创建通知? 预先感谢您的帮助
一小步
在存储库中,我设置了一个private long id;
变量。
在 onPostExecute 内部,我设置了 id=test;
,如上面的代码所示,我创建了一个如下方法:
public long getId(){
return id;
}
它是在插入方法之后从 MainActivity 调用的。 问题是,我第一次运行应用程序并创建任务时,此变量中的值始终为 0。我该如何解决这个问题?
最佳答案
这可能对你有帮助。
基于文档here (在代码 fragment 下方)
用@Insert
注释的方法注解可以返回:
-
long
对于单个插入操作 -
long[]
或Long[]
或List<Long>
对于多个插入操作 -
void
如果您不关心插入的 ID
关于java - 如何将Repository自动生成的ID返回到MainActivity?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59146861/