gpt4 book ai didi

java - SQLiteOpenHelper .update() 不持久

转载 作者:行者123 更新时间:2023-12-01 23:00:06 28 4
gpt4 key购买 nike

我的表中有一个 sortid 行,用于自定义数据顺序。

在我的 SQLiteOpenHelper 类中,我有一个 drop() 函数,它调用 .update(),并且在 loadCities() 中查询行,但我得到旧的 sortId。

这是我的部分代码:

public class TimesHelper extends SQLiteOpenHelper {
private static final String TABLE_CREATE = "CREATE TABLE " + TABLE_NAME
+ " (" + KEY__ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ [...] + KEY_SORTID + " INTEGER);";

private SQLiteDatabase mDB;
private Handler mHandler;


public SQLiteDatabase getDB() {
if (mDB == null) {
mDB = getWritableDatabase();
} else {
mHandler.removeCallbacks(mClose);
}
//useful, but i am not sure wether this is good practise, please comment...
mHandler.postDelayed(mClose, 500);
return mDB;
}

private Runnable mClose = new Runnable() {
@Override
public void run() {
if (mDB != null) {
mDB.close();
mDB = null;
}
}
};


public void drop(int from, int to) {
List<Integer> keys = new ArrayList<Integer>(Times.Cities.keySet());
Integer key = keys.get(from);
keys.remove(key);
keys.add(to, key);
getDB().beginTransaction();
for (Integer i : keys) {
ContentValues val = new ContentValues();
val.put(KEY_SORTID, keys.indexOf(i));
getDB().update(TABLE_NAME, val,
KEY__ID + "=" + i, null);//returning 1
}
getDB().endTransaction();
loadCities();

}

public void loadCities() {
HashMap<Integer, Times> cities = Times.Cities;
cities.clear();
Cursor c = getDB().query(TABLE_NAME, null, null, null, null, null,
KEY_SORTID);
c.moveToFirst();
if (c.isAfterLast()) {
c.close();
return;
}
do {
int s = c.getInt(c.getColumnIndex(KEY_SORTID));
int id = c.getInt(c.getColumnIndex(KEY__ID));
//here i still have the old values...
//do whatever
}
} while (c.moveToNext());
c.close();

}
}

我尝试了一切,但没有成功......

梅廷羽衣甘蓝

最佳答案

您忘记了setTransactionSuccessful()。调用 endTransaction() 而不回滚事务中所做的任何更改。

处理事务的首选异常安全模式是

beginTransaction();
try {
// db operations...

setTransactionSuccessful(); // didn't throw so far
} finally {
endTransaction(); // rollback or commit
}

关于java - SQLiteOpenHelper .update() 不持久,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23502167/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com