我在我的 Android 项目中使用 GreenDAO。
我已经实现了一个增量更改表,因此我可以跟踪对实体的各个更新。我想在一个“updateTask”方法中跟踪这些更改,因此无论从何处调用它,都可以更新增量表。
目前,我有一种方法可以更改 Task 实体的状态。
public void updateTaskStatus (Long taskId, String status) {
Task task = taskDao.load(taskId);
task.setStatus("Pending");
updateTask(task);
}
Run Code Online (Sandbox Code Playgroud)
然后我有我的任务更新方法。
public void updateTask (Task task) {
//Check for any changes to the Task entity in this method and update the delta table.
Task existingTask = taskDao.load(task.getId()); // <---this call returns the same reference to the task object that was passed into this method.
if (!existingTask.getStatus().equals(task.getStatus())) { //<--this is always returning false as both existingTask and task point to the same Task instance, but I want a fresh one and my current one. My problem is here!
//update delta table here with status change entry.
}
taskDao.update(task);
}
Run Code Online (Sandbox Code Playgroud)
我的问题是从 taskDao 加载任务时,总是返回相同的引用。因此,当我第一次加载任务并设置状态,然后将其传递给 updateTask 方法时,我尝试从数据库加载新副本进行比较,它实际上返回相同的引用。所以我的if (!existingTask.getStatus().equals(task.getStatus()))语句总是返回 false,因为两个引用的值是相同的。
如果我尝试调用 taskDao.refresh(existingTask),它将再次无济于事,两个引用都指向相同的 Task 实例。
如何在不影响“内存中的一个”的情况下从 greenDao 获取我的 Task 实体的新副本?
希望你能理解我的问题。
我想到了。在再次获取它之前,我只需要将我的实体从会话中分离出来。
public void updateTask (Task task) {
//Check for any changes to the Task entity in this method and update the delta table.
**taskDao.detach(task); // <--added this line of code**
Task existingTask = taskDao.load(task.getId());
if (!existingTask.getStatus().equals(task.getStatus())) {
//update delta table here with status change entry.
}
taskDao.update(task);
Run Code Online (Sandbox Code Playgroud)
}
| 归档时间: |
|
| 查看次数: |
785 次 |
| 最近记录: |