0

I have got some Objects shown in a ListView. For that reason I've got a class just for the Objects with 2 attributes: "name" and "price" (Yes, no ID, because I set the datatype in my SQLite Database to integer, primary key, autoincrement.)

In my Activity class, I've got an ArrayList filled with all of the Objects, which are in the Database (which works fine)

Now, I have added a onItemClick method.

  public boolean onItemLongClick(AdapterView<?> parent, View convertView, final int position, long id) 

And there is the problem: trying to delete the object (I've written my own delete method which works fine, but needs an ID as parameter) is not working, because the ID in the database is not equal to the POSITION in the ListView.

I've wondered about the 4th argument in the method (long id), but it's showing the value 0 for every ListView Item

Any Ideas how I can get the proper Id to each ListView Item position (which will still work fine if Items are getting deleted) ?

Charles
  • 50,943
  • 13
  • 104
  • 142
user3527860
  • 65
  • 1
  • 6
  • When you get your data from the database, why don't you just get the id as well and place it in you object class. – Parnit Apr 14 '14 at 18:19
  • true... but somehow "object.setId(cursor.getInt(0));" is just setting 0 as value, even though in the database the id is counting any ideas ? – user3527860 Apr 14 '14 at 18:30
  • hahaha nevermind, I just forgot to update the constructor it is working now thank you so much – user3527860 Apr 14 '14 at 18:39

4 Answers4

1

If your are using a CursorAdapter subclass, then your primary key should be named _id if you want to get it from the 4th parameter of onItemLongClick method.

have a look here and here

Community
  • 1
  • 1
S.Thiongane
  • 6,883
  • 3
  • 37
  • 52
0

I believe that the list builds itself from the db so if the primary key is autoincrementd it should follow the list's index? First item in db = first item in list? It would be really easier to simply add the ID in your object class tho

Tascalator
  • 462
  • 5
  • 13
0

the id of the ListView is totally separated from the id of your database. You could use the position, BUT if you delete an entry in the database the matching isn't correct anymore. I strongly recommend to load and store the database id in the object.

speedy1034
  • 304
  • 2
  • 9
0

Get the object from the Array or ArrayAdapter used to populate the listview from the position passed to onItemLongClick The example below get's the item from an ArrayAdapter that was used to populate a listview.

public boolean onItemLongClick(AdapterView<?> parent, View convertView, final int position, long id) {
    myObject = myArrayAdapter.getItem(position);
}
danny117
  • 5,581
  • 1
  • 26
  • 35