-1

I have a ListView getting data from an SQLite database.

Data:

  1. Primary Key, Name
  2. 1, "John"
  3. 2, "Mark"

My ListView shows the names.

How do I make it so when you tap on a name you get the value of the Primary Key? i.e Tapping on "Mark" would return 2

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Tim
  • 69
  • 5

2 Answers2

0

You'll need to add a click listener to your list view adapter and then return the key value when the item has been selected.

You can get the key value by doing something like this within the click code..

keyValue = cursor.getInt(cursor.getColumnIndex("key_field_name_in_table"));

There are loads of examples of list view click handling around. Here is one i found on Stack Overflow

teh_raab
  • 384
  • 1
  • 3
  • 21
  • Yes I know how to do the listener bit, I just needed to know how to get the corresponding primary key value to the name that was tapped. The getColumnIndex method above looks like it returns the correct column, but will that return the corresponding row? – Tim Oct 19 '18 at 10:53
  • In the on click you can add something like `cursor.moveToPosition(getAdapterPosition());` to ensure the cursor is pointing to the correct row – teh_raab Oct 19 '18 at 11:02
  • Ah, getAdapterPosition() looks promising. I'll try that out when I get a chance – Tim Oct 19 '18 at 11:06
  • I also found this. – Tim Oct 19 '18 at 11:14
  • public void DetailClick(View v) { ListView lv = getListView(); int position = lv.getPositionForView(v); } – Tim Oct 19 '18 at 11:14
0

Blockquote

It seems the OnItemClickListener already has a integer variable called position.

To test, in the OnItemClickListener I made a toast like this:

    Toast.makeText(getApplicationContext(),String.valueOf(position).Toast.LENGTH_LONG.show();
Tim
  • 69
  • 5