简体   繁体   中英

Best way to refresh ListView when data in cursor hasn’t changed

I have a ListView with attached custom CursorAdapter. Within the CursorAdapter bindView method I run some calculations that depend on user's chosen display units (these can be changed at any time in Settings)

Normally to update a ListView I would run:

myCursor = DB.getData();
myDataAdapter.changeCursor(myCursor);

This works fine in most cases. But if user changed their display units in Settings, above code doesn't update the ListView. I assume this is because data in the cursor hasn't actually changed.

I tried running notifyDataSetInvalidated() and notifyDataSetChanged() against the adapter, also invalidateViews() against the ListView, but none of this make any difference. What I currently do is recreate the adapter:

myCursor = db.getData();
myCursorAdapter = new myCursorAdapter(getActivity(),myCursor,0);
myListView.setAdapter(myCursorAdapter);

This works, but I don't think it's a good practice to re-create the adapter every time I need to refresh ListView... Is there a better way to do this?

EDIT:

myDataAdapter.changeCursor(myCursor) is actually working even when data in cursor hasn't changed. It was my own mistake in the Custom Cursor Adapter code that caused listview not to update unless adaptor was re-created.

notifyDataSetChanged() still doesn't work, but decided not to look into this further and just use changeCursor

The BaseAdapter method notifyDataSetChanged() should do what you want. It could be that the adapter you are passing in is not the same as the adapter the ListView is using. Try using getAdapter() instead:

((MyCursorAdapter) myListView.getAdapter()).notifyDataSetChanged();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM