Harlsten
Harlsten

Reputation: 821

Sort array adapter after item add

how can I force array adapter to sort itself. notifyDataSetChanged doesn't work. What I want to do is to add an item to array adpater and then force it to sort again. This is my adpater:

    this.noteListViewAdapter = new NoteListViewAdapter(this.GetActivityContext(), R.layout.list_view_note_item, noteItems);

    // sorting
    this.noteListViewAdapter.sort(new Comparator<NoteItem>()
    {
        @Override
        public int compare(NoteItem item1, NoteItem item2)
        {
            // TODO Auto-generated method stub
            return item2.CreationDate.compareTo(item1.CreationDate);
        };
    });

It works fine. Items are sorted. But then when I want to add new item, sorting doesn't work. Its not even called. This is how I add new item:

    this.noteListViewAdapter.add(note);
    this.noteListViewAdapter.notifyDataSetChanged();

Thank you for your help

Upvotes: 1

Views: 2312

Answers (2)

Raffy
Raffy

Reputation: 79

Don't call sort() inside notifyDataSetChanged() or you will get, guess what, a StackOverFlow ! :)

sort() already calls notifyDataSetChanged()

Upvotes: 0

Heiko Rupp
Heiko Rupp

Reputation: 30974

You would need to call sort() inside your add() method after adding the passed note to the internal list of noteItems.

Or you could call that inside notifyDataSetChanged() before calling super.notifyDataSetChanged().

I think the latter is even better, as this way you don't sort every time when batch-add()ing items.

Upvotes: 2

Related Questions