Reputation: 97
I have used sqlite database using ormlite.I have declared primary key in database as follows:In database i fetch the values and display in listview. when i delete some entry.in list view..primary key goes on increasing values.
@DatabaseField(generatedId = true,columnName = "teacher_id")
int teacherid;
try {
Toast.makeText(DetailListView.this, "Delete entry", Toast.LENGTH_LONG).show();
DeleteBuilder<TeacherDetails, Integer> deleteBuilder=teacherDao.deleteBuilder();
deleteBuilder.where().eq("teacher_address", set.teacheraddress);
deleteBuilder.delete();
stud_list = teacherDao.queryForAll();
//adapter = new UsersAdapter(DetailListView.this, stud_list);
// list.setAdapter(adapter);
list.invalidate();
teacherDao.executeRaw("delete from sqlite_sequence where name='teacher_details';");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//code for creating db.
@Override
public void onCreate (SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, TeacherDetails.class);
TableUtils.createTable(connectionSource, StudentDetails.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Unable to create datbases", e);
}
}
@Override
public void onUpgrade(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource, int oldVer, int newVer) {
try {
TableUtils.dropTable(connectionSource, TeacherDetails.class, true);
TableUtils.dropTable(connectionSource, StudentDetails.class, true);
onCreate(sqliteDatabase, connectionSource);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Unable to upgrade database from version " + oldVer + " to new "
+ newVer, e);
}
}
For example before delete 1)primary key :1 2)primary key:2(if i delete this values) 3)primary key:3
After delete 1)primary key:1 2)primary key:3(not start with primary key value 2) 3)primary key 4
This is my requirement
Upvotes: 0
Views: 148
Reputation: 46963
This is how database sequences are supposed to work. Your example is simple, but imagine a table with 10000000 entries. Imagine them being with ids the first 10000000 natural numbers. Now imagine a person goes and deletes the 345346th, then 123344th and finally 234545th. How should it know which ids are vacant, without requiring a huge number of calculations.
If your case is specific and you have just few entries, which you need to be sequential, you will have to give up on autoincrements and code it yourself. But please, consider all corner cases, because i beleive they are quite a few.
Upvotes: 1