android sqlite desc,Android SQLite - Primary Key Desc - Stack Overflow

这篇博客讨论了一个 SQLite 数据库操作的实现。首先,作者提供了一个方法 `generateId`,该方法用于从数据库中获取最小的可用 ID(如果表为空则返回 -1)。然后,这个 ID 被用于 `add` 方法中,将数据插入到表中。这种方法确保了 ID 的连续性。博客主要关注数据库操作和 ID 管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Closed. This question needs details or clarity. It is not currently accepting answers.

Want to improve this question? Add details and clarify the problem by editing this post.

Closed 7 years ago.

First create the id generator:

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;

}

this will be our initial value

we can replace it with another value

// if the table is empty returns -1

int result = -1;

then use it in the insert:

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();

}

Does anyone have another solution?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值