首先创建 id 生成器:
private int generateId() {
// if the table is empty returns -1
int result = -1;
String sql = "SELECT id FROM table order by id asc";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(sql, null);
//if any id is decremented
if (cursor.moveToFirst())
result = (cursor.getInt(0) -1);
cursor.close();
db.close();
return result;
}
这将是我们的初始值,我们可以用另一个值替换它
// if the table is empty returns -1
int result = -1;
然后在插入中使用它:
public void add(Type type) {
int id = this.generateId();
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("id", id);
cv.put("value",type.value)
...
db.insert(table, null, cv);
cv.clear();
db.close();
}
有人有其他解决方案吗?