本文介绍了OrmLiteSqliteOpenHelper onDowngrade的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ormlite for android 并且我有一个扩展 OrmLiteSqliteOpenHelper 的数据库表类.我在 google play 中有一些报告说应用程序被强制关闭是由以下原因引起的:

I'm using ormlite for android and I have a database table class that extends OrmLiteSqliteOpenHelper. I've had some reports in google play that the application had a force close caused by:

android.database.sqlite.SQLiteException: Can't downgrade database from version 3 to 2

用户可能会通过备份或其他方式降级.问题是我无法实现 SQLiteOpenHelper:

The users probably get to downgrade via a backup or something. The problem is I cannot implement the onDowngrade method that exists on SQLiteOpenHelper:

ormlite 是否支持降级?有什么解决办法吗?至少可以避免强制关闭.

Does ormlite support the downgrade? Is there any work around for this? At least to avoid the force close.

推荐答案

有趣.所以 onDowngrade(...) 方法被添加到 API 11 中.我不能只是在 ORMLite 中添加对它的支持.不幸的是,这意味着您将不得不创建自己的 onDowngrade 方法,该方法与 OrmLiteSqliteOpenHelper 中的 onUpgrade(...) 相同.类似于以下内容:

Interesting. So the onDowngrade(...) method was added in API 11. I can't just add support for it into ORMLite. Unfortunately this means that you are going to have to make your own onDowngrade method which is the same as the onUpgrade(...) in OrmLiteSqliteOpenHelper. Something like the followign:

public abstract void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion,
        int newVersion) {
    // your code goes here
}

public final void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    ConnectionSource cs = getConnectionSource();
    /*
     * The method is called by Android database helper's get-database calls when Android detects that we need to
     * create or update the database. So we have to use the database argument and save a connection to it on the
     * AndroidConnectionSource, otherwise it will go recursive if the subclass calls getConnectionSource().
     */
    DatabaseConnection conn = cs.getSpecialConnection();
    boolean clearSpecial = false;
    if (conn == null) {
        conn = new AndroidDatabaseConnection(db, true);
        try {
            cs.saveSpecialConnection(conn);
            clearSpecial = true;
        } catch (SQLException e) {
            throw new IllegalStateException("Could not save special connection", e);
        }
    }
    try {
        onDowngrade(db, cs, oldVersion, newVersion);
    } finally {
        if (clearSpecial) {
            cs.clearSpecialConnection(conn);
        }
    }
}

有关onDowngrade(...) 方法见下:

public void onDowngrade (SQLiteDatabase db, int oldVersion, int newVersion);

引用javadocs:

当数据库需要降级时调用.这与 onUpgrade(SQLiteDatabase, int, int) 方法非常相似,但只要当前版本比请求的版本更新就会调用.但是,该方法不是抽象的,因此不是客户必须实现的.如果没有被覆盖,默认实现将拒绝降级并抛出 SQLiteException

另见:

无法将数据库从版本 2 降级到 1

这篇关于OrmLiteSqliteOpenHelper onDowngrade的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 03:31