SQLiteOpenHelper .update()不会持久化

时间:2014-05-06 18:24:34

标签: java android database sqlite class

我的表格中有一个sortid行,可以自定义我的数据顺序。

在我的SQLiteOpenHelper类中,我有一个调用.update()的drop()函数,在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();

    }
}

我尝试过任何事情,但没有成功......

Metin Kale

1 个答案:

答案 0 :(得分:3)

你忘记了setTransactionSuccessful()。在没有它的情况下调用endTransaction()会回滚在事务中完成的任何更改。

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

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

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