【问题标题】:How to return the ID autogenerated from Repository to the MainActivity?如何将 Repository 自动生成的 ID 返回到 MainActivity?
【发布时间】:2019-12-02 21:22:22
【问题描述】:

我有一个无法解决的大问题。我正在开发一个“提醒应用程序”,它允许您插入备忘录并在该做的时候通知您。好吧,我在 Android 中使用 Room,当我插入新任务时,我想使用插入任务的 id 作为管理通知的 id。我有TaskViewModel 和TaskRepository。这是我写的代码:

在 DAO 中我有:

@Insert
long insert(Task task);

在我的主要活动中:

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。我该如何解决这个问题?

【问题讨论】:

    标签: java android android-studio android-room


    【解决方案1】:

    这可能会对你有所帮助。

    基于文档here(代码sn-p下方)

    带有@Insert注解的方法可以返回:

    • long 用于单次插入操作
    • long[]Long[]List&lt;Long&gt; 用于多个插入操作
    • void 如果你不关心插入的 id(s)

    【讨论】:

    • 是的,我读到了,但我不知道如何通过存储库、ViewModel 传递 ID 并将值保存在 MainActivity 中。有人可以给我看代码示例吗?我做错了什么?
    猜你喜欢
    • 2017-10-10
    • 2016-01-22
    • 1970-01-01
    • 2011-11-18
    • 2012-04-01
    • 2017-11-23
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多