fatih kiymet
fatih kiymet

Reputation: 127

RecyclerView doesn't update the UI after data changed

I am new in android development, after make a network request trying to update item view in the RecyclerView control without scrolling it. As far as I understand items gets refreshed during scroll via onBindViewHolder event.here is the code. Using notifyItemChanged method to update UI but it doesn't work until user scroll.

Note : favoriteMatches is not my data source. It is another list of objects which stores user favorites, inside onBindViewHolder event I am cheking if item is favoriteMatches.contains(match) then render as fav item.

call.enqueue(new Callback<AddRemoveFavoriteRequest.Response>() {
        @Override
        public void onResponse(Call<AddRemoveFavoriteRequest.Response> call, Response<AddRemoveFavoriteRequest.Response> response) {
            AddRemoveFavoriteRequest.Response body = response.body();
            Utilities.dismissProgressDialog(getActivity(),progressBar);

            if(body.error == null){
                if(add){
                    favoriteMatches.add(matchId);
                }
                else {
                    favoriteMatches.remove(matchId);
                }

                adapter.notifyItemChanged(absolutePosition);
                Preferences.getDefaultPreferences().edit()
                        .putStringSet(Preferences.PREF_FAVORITES,favoriteMatches)
                        .apply();

            }else{
                Utilities.showSnackBar(getActivity(),recyclerView,body.error);
            }
       }

       @Override
       public void onFailure(Call<AddRemoveFavoriteRequest.Response> call, Throwable t) {
             t.printStackTrace();
             Utilities.dismissProgressDialog(getActivity(),progressBar);

        }
});

Upvotes: 0

Views: 4894

Answers (1)

OneCricketeer
OneCricketeer

Reputation: 191681

notifyItemChanged takes the position at which the item changed.

You are adding and removing elements, so that position is going to move around. Instead, you can individually notify at positions.

int changedPosition = 0;
if(add){
    changedPosition = favoritesMatches.size();
    favoriteMatches.add(matchId);
    adapter.notifyItemInserted(changedPosition);
}
else {
    changedPosition = favoriteMatches.indexOf(matchId); // might not work
    favoriteMatches.remove(matchId);
    adapter.notifyItemRemoved(changedPosition);
}

Or, instead update the entire list

adapter.notifyDataSetChanged();

Read more about notifying the adapter, but note

a RecyclerView adapter should not rely on notifyDataSetChanged() since the more granular actions should be used.

Upvotes: 1

Related Questions