Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update values in RecyclerView on onResume()?

Tags:

android

I'm designing a news app in which I'm showing the news articles in a recyclerView. Now on clicking a news article I want to change its background color to indicate that the news item has been read.

For this, first I update a status field corresponding to the news article in my Firebase Database when the news is read. Then I check the value of this field in my recycler Adapter and change the background if the status is changed.

However since the adapter of the recyclerView is defined in the onCreateView of the fragment, the change does not take place immediately when I press the back button. Rather the changes occur when reopen the app since the onCreateView is called that time. So how do I update the adapter in onResume of the fragment and update the recyclerView accordingly?

like image 371
Sarthak Grover Avatar asked Feb 05 '23 05:02

Sarthak Grover


2 Answers

Override the onResume method and call notifyDataSetChanged:

@Override
public void onResume() {
    super.onResume();
    adapter.notifyDataSetChanged();
}

In Kotlin:

override fun onResume() {
    super.onResume()
    adapter.notifyDataSetChanged()
}
like image 54
nitinkumarp Avatar answered Feb 06 '23 20:02

nitinkumarp


Initialize and set adapter from oncreateview();

Then you only need to update adapter data and call adapter.notifyDataSetChanged(); form your onResume();

@Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
  YourAdapter adapter = new YourAdapter(listofdata);
  yourRecycleView.setAdapter(adapter);
 }

@Override
public void onResume() {
super.onResume();
listofdata.clear();  //Reset before update adapter to avoid duplication of list
//update listofdata
adapter.notifyDataSetChanged();
}
like image 31
EKN Avatar answered Feb 06 '23 19:02

EKN