0

Although I have managed to find a workaround for this problem (see end) I would very much like to know if there is a better way of doing it. I am struggling to find an answer using Google as I am not sure how to phrase the question properly so if this has already been answered: my apologies, and could you please provide a link. I am making use of the standard MVVM setup based on various beginner tutorials online, this includes: Room database, repository, DAO with a LiveData list of objects, ViewModel, and RecyclerView.Adapter.

I have two fragments, A and B. Fragment A holds a recyclerView of items while fragment B is brought forward to enable editing when an item in the recyclerView is clicked. To populate the views of fragment B I use the getItem() method of my RecyclerView.Adapter class (which performs a get() call on my list, list C, of objects) to create an object, object D. This allows me to pass object D around fragment B as needed.

On to the problem: What I have found is that if I make any changes to this object D, the changes are carried through to list C. This means if I make changes to object D, then leave fragment B without making any attempts at saving the changes, fragment A shows the changes that were made. This is problematic as it gives the user the impression that the changes were saved but the underlying database has not been updated, only the LiveData list C.

My workaround: This methods works but I would think there are better solutions available. When fragment B is brought forward I create a temporary object, object E, using the getItem() method of the RecyclerView.Adapter class. I then create object D using object E's getter methods. My guess is that the getItem() method is returning a reference (or something) to the LiveData object, as opposed to a copy of the object, but I really do not know.

I hope this makes sense, if you need anything else from me please let me know.

Rory
  • 51
  • 1
  • 5
  • 1
    this might be related to your issue, https://stackoverflow.com/questions/62363268/object-is-changed-after-sending-it-to-another-fragment/62364317#62364317 – Mohammed Alaa Jul 22 '20 at 17:56
  • Thanks! I was not aware that "Object variables in Java always point to the real object in the memory heap" [link](https://www.infoworld.com/article/3512039/does-java-pass-by-reference-or-pass-by-value.html) – Rory Jul 23 '20 at 05:48

1 Answers1

0

Thanks to Mohammed Alaa for this redirection: https://stackoverflow.com/a/62364317/9046317: essentially object references are passed by value.

Rory
  • 51
  • 1
  • 5