【问题标题】:SQLiteOpenHelper .update() does not persistSQLiteOpenHelper .update() 不持久
【发布时间】:2014-06-23 12:11:00
【问题描述】:

我的表中有一个 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();

    }
}

我尝试了任何方法,但都没有成功...

梅丁羽衣甘蓝

【问题讨论】:

    标签: java android database sqlite class


    【解决方案1】:

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

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

    beginTransaction();
    try {
         // db operations...
    
         setTransactionSuccessful(); // didn't throw so far
    } finally {
         endTransaction(); // rollback or commit
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-22
      • 1970-01-01
      • 1970-01-01
      • 2012-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多