Reputation: 738
I have a sortid row in my table to have a custom order of my data.
in my SQLiteOpenHelper class, i have a drop() function which calls .update(), and in loadCities() the rows are queried but i get the old sortId.
here are parts of my code:
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();
}
}
i tried anything, but without success...
Metin Kale
Upvotes: 0
Views: 55
Reputation: 152857
You forgot setTransactionSuccessful()
. Calling endTransaction()
without it rolls back any changes done within the transaction.
The preferred, exception-safe pattern to handle transactions is
beginTransaction();
try {
// db operations...
setTransactionSuccessful(); // didn't throw so far
} finally {
endTransaction(); // rollback or commit
}
Upvotes: 3