Home » Android » android – notifyDataSetChanged() in Fragment is not refreshing listview

android – notifyDataSetChanged() in Fragment is not refreshing listview

Posted by: admin June 15, 2020 Leave a comment

Questions:

I’m trying to display a list of items fetched from a url but I only want to fetch 20 of them at a time… so I’ve implemented an OnScrollListener to fetch the items when the users is on the last item of the listview.

The items are fetched but my only problem is that the listview is not updated: here’s my code so far:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    parentView = inflater.inflate(R.layout.activity_event_speakers_alphabetically, container,false);
    listView = (ListView) parentView
            .findViewById(R.id.speakersAlphabeticallyActivityList);
    nameOrderedMembers.addDataBatch(communityMembers);
    nameOrderedAdapter = DelegateViewStateAdapterFactory
            .makeUserListAdapter(getActivity(),
                    nameOrderedMembers.getSortedData(), DelegateViewStateAdapterFactory.OrderType.NAME);
    listView.setAdapter(nameOrderedAdapter);
    AQuery aQuery = new AQuery(listView);
    aQuery.id(R.id.speakersAlphabeticallyActivityList).scrolled(new EndlessScrollListener());
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
            if (nameOrderedAdapter.getItem(arg2) instanceof User) {
                User u = (User) nameOrderedAdapter.getItem(arg2);
                Intent i = new Intent(getActivity(),
                        UserProfileFragmentActivity.class);
                startActivity(i);
            }
        }
    });

    return parentView;
}

Now – in the AsynkTask in the onPostExecute method – i notify the adapter like this:

communityMembers.addAll(newMembers);
getActivity().runOnUiThread(new Runnable() {
    @Override
    public void run() {
    nameOrderedAdapter.addAll(communityMembers);
    nameOrderedAdapter.notifyDataSetChanged();
    }
  });

but the listview doesn’t refresh – only if I go back and reopen the activity – the new data is shown.

So how can I notify the adapter that there’s new data to display?

How to&Answers:

call listView.invalidateViews() after notifyDataSetChanged()

Answer:

add below line after nameOrderedAdapter.notifyDataSetChanged(); :

listView.setAdapter(nameOrderedAdapter);

Answer:

use

notifyDataSetInvalidated()

method
if you are using any custom ListView or Custom GridView like /
HorizontalListView