Search code examples
androidsqliteandroid-listviewcursorandroid-cursoradapter

can't getting data from cursor adapter


I have a ListView (in an Activity and not in a ListActivity) that utilizes a custom cursor adapter to get some data from my local db and show them inside the ListView.

lv.setOnItemClickListener(new OnItemClickListener()
{
   @Override
   public void onItemClick(AdapterView<?> arg0, View view, int position, long id)
      {
            Log.i(tag, "position = " + position);
        Log.i(tag, "id is : " + id));
      }
});

Assume my database columns are the following :

id, name, surname, dob, height, gender, placeOfBirth, maritalStatus.

However, I am showing in my listview (row.xml) only the name and surname. But whenever the user clicks on a certain row in the list, I want to retrieve the rest of the data too, for example, the id, or the gender of the row clicked.

The issue is that, I am not showing all the info from the db row in my list, however, when the user presses on the list I need to retrieve some of the data for that list. How can I do that here ?

The below method does not work, because I am not in a ListActivity, and just Activity.

public void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position,  id);

Cursor c = ((SimpleCursorAdapter)l.getAdapter()).getCursor();
c.moveToPosition(position);
//get the data...
}

Solution

  • The arg0 parameter in your OnItemClickListener is the ListView. However, you can just do

    lv.setOnItemClickListener(new OnItemClickListener() {
       @Override
       public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
                // This will get the cursor from the adapter, already moved to position
                Cursor cursor = (Cursor) mCursorAdapter.getItem(position)
                //get the data...
          }
    });