4

I am using GreenDAO in my Android project.

I've implemented a delta change table so I can track the individual updates to an entity. I want to track these changes in one single "updateTask" method, so no matter where its called from, the delta table can be updated.

Currently, I have a method which changes the status of a Task entity.

public void updateTaskStatus (Long taskId, String status) {
    Task task = taskDao.load(taskId);
    task.setStatus("Pending");
    updateTask(task);
}

I then have my task update method.

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);
}

My problem is that when loading a Task from the taskDao, the same reference is always returned. So when I load the Task for the first time, and set the status, then pass it to the updateTask method and in there I try to load a fresh copy from the database to compare to, it actually returns the same reference. So my if (!existingTask.getStatus().equals(task.getStatus())) statement always returns false, as the values for both reference are the same.

If I try and call taskDao.refresh(existingTask), it wont help as once again, both references point to the same instance of Task.

How can I get a fresh copy of my Task entity from greenDao without affecting the "one in memory" ?

Hope you can understand my question.

dleerob
  • 4,951
  • 4
  • 24
  • 36
  • Apparently I'm not allowed to duplicate my answer here, but see my answer on this https://stackoverflow.com/a/47401143/2775083 post regarding why this behaviour is occuring – TheIT Nov 22 '17 at 20:23

1 Answers1

5

I figured it out. I simply had to detach my entity from the session before getting it again.

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);

}

dleerob
  • 4,951
  • 4
  • 24
  • 36
  • 1
    Thank you. I've been trying to solve this problem for a while, and also had no answers on my own thread. This will definitely help. – fehbari Jul 22 '15 at 19:12