-1

I have a SQLite database in my android application which holds multiple username/password entries, this content is placed into a ListView.

What I would like to achieve, is when an item is longpressed, it is removed from the list, but I'm encountering an issue.

I use the following code to remove an entry from the database:

    public void deleteEntry(int ID) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_LOGINS, KEY_ID + " = ?",
            new String[]{Integer.toString(ID)});
    db.close();
    }

The data is stored in the database in the following manner:

--------------------------
1|server|username|password
2|server|username|password
3|server|username|password
4|server|username|password
--------------------------

Now if I was to mark entry #2 for deletion, I would end up with the following

--------------------------
1|server|username|password
3|server|username|password
4|server|username|password
--------------------------

Which causes issues attempting to access the other entries, as I do all my lookups using the first field. Using the position from my OnItemLongClickListener, if I was to press the 2nd item in the list, it would be searching for an item with ID of 2.

How can I update the entries in my database so that my ID field will be sequentially numbered? Is there a better alternative to using an ID field?

keag
  • 299
  • 2
  • 15

2 Answers2

0

It would be best to simply reset your identity columns, you can refer to this question: SQL Server Reset Identity Increment for all tables

Note that relying on all your columns being incremental is fairly bad practice, I would advise you link each row in the database to a row in your program so when loading, you select each item from the database and create a row for it in your program, this eliminates this issue.

Community
  • 1
  • 1
dwilson390
  • 83
  • 1
  • 1
  • 6
0

I can suggest a simple change.

When you load the list (using the CursorLoader if you are using so), maintain a list of ids that are loaded. This can be achieved by declaring a global ArrayList<Integer> holding the ids of the loaded fields. Now using the onLongItemClicked or likewise methods, you can simply delete the rows from the database using the IDs by using get(position) method on the ArrayList<Integer> object to get the ID currently held by a row item. Finally after deleting from the database, delete the ID from the ArrayList as well, and you're ready for another round of deletion.

TeChNo_DeViL
  • 739
  • 5
  • 11