FET
FET

Reputation: 942

Sort ListView in ListActivity

I've created a ListActivity (yeah, the one without an XML layout) which displays the values got from an ArrayList<String>, via an adapter.

The fact is that the last String added to the ArrayList, is the latest to appear on the ListView aswell, instead I want to sort the ListView so that the last item added will be the first one on top in the ListView, how to do it?

Look, this is a snippet of my application, about the onCreate() method of the ListActivity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent = getIntent();
    ArrayList<String> history = intent.getStringArrayListExtra("HistoryList");

    ListView historyList = getListView();
    ArrayAdapter<String> listAdapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, history);
    historyList.setAdapter(listAdapter);
}

Upvotes: 0

Views: 83

Answers (3)

user2413972
user2413972

Reputation: 1355

Nothing complicated. You just needed to reverse the list history.

Collections.reverse(history);

You should read a little about the theory of Java and learn how to look for. Otherwise, nothing good is not over. The code would look like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent = getIntent();
    ArrayList<String> history = intent.getStringArrayListExtra("HistoryList");
    Collections.reverse(history);
    ListView historyList = getListView();
    ArrayAdapter<String> listAdapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, history);
    historyList.setAdapter(listAdapter);
}

Upvotes: 1

Bharathwaj Murali
Bharathwaj Murali

Reputation: 31

Try to write a Comparator to sort the string.

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1006614

how to do it?

Re-order history to be in the order that you want, such as via Collections.reverse().

Upvotes: 1

Related Questions