0

I have a database with a table that stores int and string. The integer value is the primary key. I have created a function to just fetch the strings from the database and store them in a list which is then applied to the ListView using an ArrayAdapter as shown below.

List<String> list = db.getAllStringNotes();

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_activated_1, list);
listview.setAdapter(adapter);
listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

The trouble is deleting from this listview. Since the primary key is not present along with the string, I was deleting using the position of the item selected from the list view. But that obviously messes up things if I'm removing an entry from the middle of the list.

So was wondering if I could add the primary key i.e. an integer value to this list view along with the String but not display the integer value?

Prathamesh Shetye
  • 915
  • 2
  • 8
  • 27

3 Answers3

2

The simple thing is create two List,

1. String - Stored String notes
2. Integer - Stored all Primary Keys

So whenever user click on Listview user get its position, and based on that position get primary key value from second list and then perform your delete query.

Kitkat
  • 77
  • 16
Chirag
  • 56,621
  • 29
  • 151
  • 198
0

There are many ways to do this: but as you are already using an ArrayList so i would suggest just make another arraylist while fetching from database:

So while deleting using the position : Use the Primary Key from the PrimaryKeyArrayList and delete values from both the ArrayList;

With this you will get exactly what you need;

AabidMulani
  • 2,325
  • 1
  • 28
  • 47
  • Yeah... thought of this the first time, but wanted a cleaner implementation. Could you suggest what are the other ways of getting something like this done? – Prathamesh Shetye Jan 13 '14 at 07:12
0

Follow these Steps:

  1. Create bean.java file that will have your db value
  2. Create CustomAdapter.java to pupulate the items and handle the delete operation
  3. Create delete method in your adapter and pass the selected bean object to delete from DB and ArrayList.
  4. after deletion call notifyDatasetChanged method to reflect the change in list

EDIT:

Bean File:

public class MyDB_Bean{
   public int id;
   public String data;
   MyDB_Bean(int id,String data){
     this.id=id;
     this.data=data;
   }
}

Calling from Activity

ArrayList<MyDB_Bean> list = db.getAllStringNotes();
MyArrayAdapter adapter = new MyArrayAdapter<String>(this,list);
listview.setAdapter(adapter);
listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

For CustomAdapter follow these tutorials

http://www.ezzylearning.com/tutorial.aspx?tid=1763429

Custom Adapter for List View

http://www.vogella.com/tutorials/AndroidListView/article.html

http://learnandroideasily.blogspot.in/2013/06/listview-with-custom-adapter.html

Community
  • 1
  • 1
dinesh sharma
  • 3,312
  • 1
  • 22
  • 32