Search code examples
androidandroid-intentandroid-activityandroid-recyclerview

Updating the same variable between two activities and the UIs in both activities' RecyclerView


I have two activities which share an exact same list, ListA, that has a property called amount.

In my first activity, I have:

  • A RecyclerView with ViewHolders. Inside each of this ViewHolder, I have a button to manipulate the amount of an item in ListA (each ViewHolder has an item inside ListA which is associated with it). This RecyclerView has two types of ViewHolder: Header and Item. The Item ViewHolder shows the amount of the item inside ListA it is associated with.
  • A Button to go to the second activity

In my second activity, I have:

  • The list from first activity (ListA) copy (passed using Intent and Parcelable)
  • A RecyclerView that is basically the same (information-wise) as the one in first activity with added functionalities. One of the functionalities includes manipulating the amount of an item in ListA. However, this RecyclerView only has one ViewHolder type (without Header). Also, there are some extra layouts that are present in the Item ViewHolder (because of the added functionalities).
  • A Button to return to the first activity

I want to:

  • Pass ListA from first activity to second activity and vice-versa
  • Update UI in first activity's RecyclerView's ViewHolders when second activity manipulates ListA and goes back to first activity; and vice-versa

What is the best way to do this? Currently, I'm passing ListA as a Parcelable Intent to second activity. However, I found it hard to update the UI accordingly on my first activity's RecyclerViews Item ViewHolder. This is because the callback passed to update its Item ViewHolder's UI requires the specified id of the layout that represents amount is triggered by the button press (in onBindViewHolder), which I am not pressing when I'm returning to the first activity.


Solution

  • Room with live data resolve your problem. https://developer.android.com/topic/libraries/architecture/livedata If you don't wanna use internal database you could try use 2 Fragments in one Activity instead of 2 Activity and manage data in the activity(or it's presenter, viewmodel ect...)