问题
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...
}
回答1:
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...
}
});
回答2:
Inside the getView
method you should use something like this
view.setTag(data); // you can pass here your specific data for each item
Supposing your data is just an integer, then you can get this value from the onItemClick()
in this way:
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Integer data = (Integer) view.getTag();
// your operation
}
来源:https://stackoverflow.com/questions/19210446/cant-getting-data-from-cursor-adapter