I have two activities where they have almost same data, I am using same Adapter, But the problem is how to sync data.
E.g.
Activity A has recyclerview where it has like buttons in each row with unique id. Activity B also have same recyclerview but with some filter mechanism so it is not going to show all row, my question is how to handle like button state in Activity A and Activity B, such that if I click on activity B's like button than activity A's like button will automatically gets checked and vice versa.
You should use common data source for both the recycler views.
- Get data from API
- Save data in your local db
- Feed the data to your Activity A recycler view
- Feed the same data to your Activity B recycler view
- All the changes you make to data should be in local db so both the
views can update automatically.
you can use static modifier
- define BaseRecyclerView which has a static list of the items
- extend CustomRecyclerView's from BaseRecyclerView
- when you manipulate the items in list such as setting like flag the list in two CustomRecyclerView's will be changed because of static modifier
Manage Locally:
Your same list of data should be accessible in both of the activities. You can save that list in your application class. And if you don't want to save in Application class then on every switch of Activity you have to pass that list data between both activities.
Next thing in Model class you have to make one more variable to save a state for like button, once you make it like then I should save that value and when you went to retrieve that same list data it will give you updated data for like button event.
Through code you can achieve:
class MyApplication extends Application{
public static ArrayList<MyModel> myModelList = new ArrayList<>();
}
class MyModel{
public boolean isLikeSelected;
}
Activity A:
onLikeClick(int position){
MyApplication.myModelList.get(position).isLikeSelected = !MyApplication.myModelList.get(position).isLikeSelected;
adapter.notifyItemChanged(position);
}
Activity B:
onLikeClick(int position){
MyApplication.myModelList.get(position).isLikeSelected = !MyApplication.myModelList.get(position).isLikeSelected;
adapter.notifyItemChanged(position);
}
Here your application class is having static ArrayList which can be accessible throughout the app and have a stable and updated record of list data.
Using Server:
On every click at like button you will update to the server for the event and next time on Activity switch you will get updated list from the server, so no need to worry in case of server management.