Mike Baxter
Mike Baxter

Reputation: 7268

Identifying items in listview

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

Answers (4)

Samuel
Samuel

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

NeilS
NeilS

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

nidhi_adiga
nidhi_adiga

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

Malachiasz
Malachiasz

Reputation: 7226

  • You can keep your UUID in an array connected with ListView through custom Adapter
  • additionally you can store this UUID in view with use of setTag() passing UUID to the view in your custom adapter.

Upvotes: 0

Related Questions