Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display new items at the top of a ListView

I'm using a list to populate a ListView (). The user is able to add items to the list. However, I need the items to be displayed at the top of the ListView. How do I insert an item at the beginning of my list in order to display it in reverse order?

like image 423
rphello101 Avatar asked Aug 31 '12 19:08

rphello101


5 Answers

You can add element at the beginning of the list: like

arraylist.add(0, object)

then it will always display the new element at the top.

like image 110
sinay Avatar answered Sep 30 '22 08:09

sinay


Another solution without modifying the original list, override getItem() method in the Adapter

@Override
public Item getItem(int position) {
    return super.getItem(getCount() - position - 1);
}

Updated: Example

public class ChatAdapter extends ArrayAdapter<ChatItem> {
public ChatAdapter(Context context, List<ChatItem> chats) {
    super(context, R.layout.row_chat, chats);
}

@Override
public Item getItem(int position) {
    return super.getItem(getCount() - position - 1);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if(convertView == null) {
        convertView = inflater.inflate(R.layout.row_chat, parent, false);
    }

    ChatItem chatItem = getItem(position);
    //Other code here

    return convertView;
}

}

like image 34
mes Avatar answered Nov 09 '22 02:11

mes


You should probably use an ArrayAdapter and use the insert(T, int) method.

Ex:

ListView lv = new ListView(context);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.id...);
lv.setAdapter(adapter);
...
adapter.insert("Hello", 0);
like image 35
aymeric Avatar answered Nov 09 '22 03:11

aymeric


By default list adds elements at bottom. That is why all new elements you add will show at bottom. If you want it in reverse order, may be before setting to listadapter/view reverse the list

Something like:

Collections.reverse(yourList);
like image 20
kosa Avatar answered Nov 09 '22 03:11

kosa


The ListView displays the data as it is stored in your data source.

When you are adding in your database, it must be adding the elements in the end. So, when you are getting all the data via the Cursor object and assigning it to the ArrayAdapter, it is in that order only. You should basically be trying to put data in the beginning of the database, rather that in the end, by having some time-stamp maybe.

Using ArrayList, you can do it by Collections.reverse(arrayList) or if you are using SQLite, you can use order by.

like image 3
Swayam Avatar answered Nov 09 '22 03:11

Swayam