Reputation: 7268
I am retrieving data from an sqlite database via a SimpleCursorAdapter
, and displaying the results on a ListView
. The database holds contact information along with an ID string. The two items I am displaying on the listview item are a person's name and their phone number, but I am not displaying the ID string (UUID).
So when the user presses on an item in this listview, how can we identify the corresponding row in the database? The item only contains name and number but not the ID column, meaning I cannot then find the appropriate row in the database.
How can I get around this problem without displaying the long UUID string in the list item?
Upvotes: 0
Views: 393
Reputation: 17171
Make your cursor that you pass to the SimpleCursorAdapter
include the UUID. Just because the cursor contains the UUID doesn't mean that it has to display it. Then when you get the position of the item that was clicked in OnItemClickListener.onItemClick(), move your cursor to this position with Cursor.moveToPosition() and get the UUID with Cursor.getString().
Another way (more elegant) is to call getAdapter() on the AdapterView passed to onItemClick and then cast the adapter as a CursorAdapter and call get getItem() on the cursor adapter. This should return the cursor object set at the position specified.
Upvotes: 1
Reputation: 635
The OnItemClickListener's onItemClick() method passes you the position in the list, and Adapter has a method getItem(int position). Cast the result from getItem() to a Cursor, this will be your cursor initialised to point to the row you clicked, so you can then get any data that was in your original query, regardless of what is in any views.
e.g.: cursor.getString(cursor.getColumnIndex("phoneNumber")));
Upvotes: 1
Reputation: 1124
In your row layout for your ListView
add another TextView
and make this TextView
invisible.
While initializing your SimpleCursorAdapter
add _id
that you are getting from the database to this TextView
. As this TextView
is invisible it won't be displayed.
String[] from = new String[] { "name", "_id" };
int[] to = new int[] { R.id.name, R.id.your_hidden_textview_id };
SimpleCursorAdapter sadapter = new SimpleCursorAdapter(this,
R.layout.ur_row_layout, ur_cursor, from, to);
In your OnItemClick
for ListView
just use below code to get the Contact ID
public void onItemClick(AdapterView<?> arg0, View view, int pos, long arg3) {
TextView contactid = (TextView) view.findViewById(R.id.your_hidden_textview_id);
String Contact_id = contactid .getText().toString();
}
Upvotes: 1
Reputation: 7226
Upvotes: 0