SqliteOpenHelper的onUpgrade()死活不啟動並執行解法

來源:互聯網
上載者:User

自己的機器 android 2.3,刷的小米系統,曾經執行成功過一次,前後傳的版本號碼也正確,後來死活不執行,確實是調用的getWritableDatabase(),看了Android源碼,也沒發現異常。

百思不得其解!換了公司的一台測試機,又可以。

由此暫時斷定這個onUpgrade不靠譜,自己寫了一套升級sqlite資料庫的邏輯。

在assets下做一個update.sql檔案,然後讀取檔案,一行行的執行sql;若升級成功,在庫裡面寫個標記。

注意:update.sql裡面,一個完整的操作,其包含的句子需要合并成一行。

代碼如下(只是思路,不可直接copy使用):

    private void updateDB() {        SqliteHelper sqliteHelper = SqliteHelper.getInstance(this);        if (!("" + Config.SQLITE_DB_VERSION)                .equals(sqliteHelper.getValue(Configuration.DB_VERSION))) {            LogUtil.i(TAG, "=====資料庫升級開始=====");            // sqliteHelper.beginTransaction();            try {                InputStream in = this.getAssets().open("update.sql");                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));                String tmpStr = null;                StringBuffer sql = new StringBuffer();                while ((tmpStr = bufferedReader.readLine()) != null) {                    sql.append(tmpStr);                    sql.append("\n");                    if (tmpStr.trim().endsWith(";")) {                        sqliteHelper.execSQL(sql.toString());                        sql = new StringBuffer();                    }                }                bufferedReader.close();                in.close();                // sqliteHelper.setTransactionSuccessful();                sqliteHelper.setValue(Configuration.DB_VERSION, "" + Config.SQLITE_DB_VERSION);                LogUtil.i(TAG, "=====資料庫升級成功!=====");            } catch (Exception e) {                LogUtil.e(TAG, e.getMessage());            } finally {                // sqliteHelper.endTransaction();            }        }    }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.