What is the intent of the methods getItem and getItemId in the Android class BaseAdapter?

Viewed 59887

I'm curious about the purpose of the methods getItem and getItemId in the class Adapter in the Android SDK.

From the description, it seems that getItem should return the underlying data. So, if I have an array of names ["cat","dog","red"] and I create an adapter a using that, then a.getItem(1) should return "dog", correct? What should a.getItemId(1) return?

If you've made use of these methods in practice, could you provide an example?

7 Answers

getItem or getItemId are few method mainly designed to attached data with items in the list. In case of getItem, you can pass any object that will attach to the item in the list. Normally people return null. getItemId is any unique long value you can attach with the same item in the list. People generally return the position in the list.

What's the use. Well, as these values are bound to the item in the list, you can extract them when user clicks on the item. These values are accessible through AdapterView methods.

// template class to create list item objects
class MyListItem{
    public String name;
    public long dbId;

    public MyListItem(String name, long dbId){
        this.name = name;
        this.dbId = dbId;
    }
}

///////////////////////////////////////////////////////////

// create ArrayList of MyListItem
ArrayList<MyListItem> myListItems = new ArrayList<MyListItem>(10);

// override BaseAdapter methods
@Override
public Object getItem(int position) {
    // return actual object <MyListItem>
    // which will be available with item in ListView
    return myListItems.get(position);
}

@Override
public long getItemId(int position) {
    // return id of database document object
    return myListItems.get(position).dbId;
}

///////////////////////////////////////////////////////////

// on list item click, get name and database document id
my_list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        // extract item data
        MyListItem selectedItem = (MyListItem)parent.getItemAtPosition(position);      
        System.out.println("Your name is : " + selectedItem.name);

        // extract database ref id
        long dbId = id;

        // or you could also use
        long dbId = parent.getItemIdAtPosition(position);
    }
});

in case your adapter ui change according to position use this two methods

@Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }
Related