ronida
ronida

Reputation: 11

How to get _id from listView (database) [android]

I have a problem with receiving _ID value when an item is clicked on listView.

I have this code:

List<SavedSearch> values =  mydb.getAllSavedSearches();

      ArrayAdapter<SavedSearch> adapter = new ArrayAdapter<SavedSearch>(this,
                android.R.layout.simple_list_item_1, values);
      //adding it to the list view.
      obj = (ListView)findViewById(R.id.listView1);
      obj.setAdapter(adapter);

      obj.setOnItemClickListener(new OnItemClickListener(){

     @Override
     public void onItemClick(AdapterView<?> parent, View view, int position,
     long id) {

And my problem is that i want in onItemClick to somehow get the _ID value from database of clicked item in listView. int position and long id both are returning just position on the list. Thanks for help, and I can say that any of previous topics helped me.

Upvotes: 0

Views: 2292

Answers (2)

ZakDaniels99
ZakDaniels99

Reputation: 505

If you're using a database I would suggest you do not use an ArrayAdapter and instead use a CursorAdapter. Then simply call the method getItemId() from your CursorAdapter to retrieve the id of an item at a given position. So, do this:

CursorAdapter adapter = new CursorAdapter(Context yourAppContext, Cursor yourDBCursor, false);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(adapter);
obj.setOnItemClickListener(new OnItemClickListener(){

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {

    adapter.getItemId(position); // This is the _ID value
}

Upvotes: 1

Amsheer
Amsheer

Reputation: 7131

This is just the suggestion. I am not sure this will solve the issue. Method 1: Whenever you load the listView just set the id for the row and you can get the id from onItemClikListener method

Method 2: Add an texView (set visibility gone) and set text as your id and get id using getText() method

Note

Don't use position this is always changing when the listview is reCycling.

Upvotes: 0

Related Questions