Return object from CursorAdapter.get()

人盡茶涼 提交于 2019-12-03 12:38:24

Now I'd like to have a Person get(int i) method from cursor adapter...

This seems like a strange request. I would pass the Cursor itself (or the Cursor returned from CursorAdapter's getItem()) to a regular method in my Activity instead. But here are the basic steps to create a Person get() method.

Create your Person class:

public class Person {
    long id;
    String firstName;
    String surname;
}

And in your custom CursorAdapter simply use a method like this:

public Person get(int position) {
    Cursor cursor = getCursor();
    Person person;
    if(cursor.moveToPosition(position)) {
        person = new Person();
        person.id = cursor.getLong(cursor.getColumnIndex("_id"));
        person.firstName = cursor.getString(cursor.getColumnIndex("firstName"));
        person.surname = cursor.getString(cursor.getColumnIndex("surname"));
        results.add(person);
    }

    return person;
}
urSus

well just use the adapter.getItem() and cast it to Cursor, and there is no need to move the cursor manually like in accepted answer

Cursor cursor = (Cursor) myCursorAdapter.getItem(position);
String myColumnValue = cursor.getString(cursor.getColumnIndex("YOUR_COLUMN_NAME"));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!