Rowan Freeman
Rowan Freeman

Reputation: 16358

How do I refresh a ListFragment efficiently?

I have a ListFragment with an ArrayAdapter to display a list of objects. I want to refresh the ListFragment's contents. The items themselves change their text a little and also change their order. I have over one hundred items and the only way I've found to do this is clear the list and re-add them, but this feels ineffcient.

For example:

ListFragment display unordered:

Object A
Object D
Object F
Object B
Object E
Object C

ListFragment display ordered:

Object A
Object B
Object C
Object D
Object E
Object F

I set up my ArrayAdapter like this:

mAdapter = new ArrayAdapter<Store>(mContext,
    android.R.layout.simple_list_item_1,
    OtherClass.list);
mAdapter.setNotifyOnChange(true);
setListAdapter(mAdapter);

"OtherClass" is:

public class OtherClass extends Object {

    public ListArray<Object> list;
    ...
}

The code in question:

mAdapter.clear();
for (Object o : list) {
    mAdapter.add(store);
}

I've already read a lot of answers about how it works and how to use mAdapter.notifyDataSetChanged() but none of them solve my problem or answer my question. Is the only way to refresh the list done by adding/removing something from the list?

Upvotes: 1

Views: 3483

Answers (2)

Rowan Freeman
Rowan Freeman

Reputation: 16358

OP here. My solution is to stick to my original method which is: If you want to modify the list slightly, but have the list refresh so it's updated and also keep the scroll position then the only way to do this is to clear() and refill the list.

Source: http://vikinghammer.com/2011/06/17/android-listview-maintain-your-scroll-position-when-you-refresh/

Upvotes: 0

dumamilk
dumamilk

Reputation: 2153

Whatever you are attaching your adapter to, like say a listView, it can be unattached by setting it to null or to something else.

So instead of the code in question:

1). Sort the list. 2). Then call:

mAdapter = new ArrayAdapter<Store>(mContext,
    android.R.layout.simple_list_item_1,
    sortedList);
setListAdapter(mAdapter);

I hope this helps, as your question is still a little unclear. Generally if you have a list generated by an adapter, you dont want to be manually digging through the list as it is auto generated for you and doing so takes away from its ease of use.

Upvotes: 2

Related Questions