SQLiteReadOnlyDatabaseException but the database is writable

谁说我不能喝 提交于 2019-12-13 01:32:13

问题


I am using SQLite on Android, ICS. When I make an update, I get a SQLiteReadOnlyDatabaseException. That was weird because i created it with SQLiteOpenHelper.getWritableDatabase(). Also, I tested if the database is readonly just before the update occurs with myDB.isReadonly(). This exception doesn't occur on Gingerbread. I suspect it has something to do with different versions of sqlite across android versions.

Here is my code for the creation of the database.

protected static class DBHelper extends SQLiteOpenHelper {
    DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CreateStatements.CREATE_MOVIES);
...

}

public class DBAdapter {
    public static final String PACKAGE_NAME =     
    protected DBHelper dbHelper;
    protected Context context;
    protected SQLiteDatabase myDB;
    public CreateStatements statement;

    public DBAdapter(Context context) {
        this.context = context;
    }

    public void open() throws SQLException {
        dbHelper = new DBHelper(context);
        myDB = dbHelper.getWritableDatabase();
        myDB.setLockingEnabled(false);
    }

    public void close() {
        myDB.close();
    }
...

}

回答1:


I recently faced. Here is how it can be solved:

try{
   myDB = dbHelper.getWritableDatabase();
} catch (SQLiteReadOnlyDatabaseException e){
   Log.d(TAG, "SQLiteReadOnlyDatabaseException");
   startActivity(new Intent(context, MainActivity.class));
}

When the database is updated, it retains some connection with the old database. When new DBHelper(context) is executed again after database upgrade, the helper links back to the old database. Hence you need to close this class and reinitialize it. In my case MainActivity is the class that first initialized the dbHelper. So when the exception is caught and the activity is restarted, the connection to the old database is removed and it works fine.



来源:https://stackoverflow.com/questions/12990391/sqlitereadonlydatabaseexception-but-the-database-is-writable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!