我的表中有一个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
}

10-07 12:26