Reputation: 2465
I have a tables in android SQLite and I am trying to figure out how to reset the KEY_ID
, I read that: DELETE FROM tablename
should delete everything and reset the autoincremement field back to 0 but when I do this it just deletes the data. When a new record is inserted the autoincrement picks up where it left off before the delete. I have implemented a longitemclicklistner
on list, it gets the position and i want to delete the particular item from the list.
Here is my code
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
getWritableDatabase().delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) } );
db.close();
}
Here is the code in onlongclicklistner
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
// TODO Auto-generated method stub
Log.v("long clicked","pos"+" "+pos);
final int p=pos+1;
final AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this);
b.setIcon(android.R.drawable.ic_dialog_alert);
b.setMessage("Are you sure you want to DELETE this Entry?");
b.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// continue with delete
db.getWritableDatabase();
db.deleteContact(db.getContact(p));
Intent i = new Intent(MainActivity.this,MainActivity.class);
startActivity(i);
}
});
b.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// do nothing
}
});
b.show();
}
The problem is, id1
is created then id2
is created but when i delete id2
and create a new contact, it gets the id3
. i want it to get id2
Upvotes: 0
Views: 1713
Reputation: 58
Why would you need that? It'll make inserts extremely slow. Suppose you have data 1,2,3,4....700, and you deleted 2 what would you do? move all the numbers up? (re-insert)?
or you'll set the next insert index to 2? right then... now delete 18, 45, 70. And insert a new row. After inserting to 18... it has to search for 45? lets say you keep a track of all the empty spaces as well for now, even then how would you cater for removing in random order 205, 102, 300, 50
You can use heap for storing available indexes, but it makes no sense as well. Maybe if you have some specific use case and share that with us we'll be able to help you better.
Upvotes: 4
Reputation: 152867
That's a feature of AUTOINCREMENT
. To make the keys reused, change the column definition from
INTEGER PRIMARY KEY AUTOINCREMENT
to just
INTEGER PRIMARY KEY
Further reading: http://sqlite.org/autoinc.html
Upvotes: 5