【问题标题】:Own SQLite Database and onUpgrade拥有 SQLite 数据库和 onUpgrade
【发布时间】:2012-08-21 03:33:02
【问题描述】:

我使用本教程来创建和填充我自己的安卓 SQLite 数据库。 http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications

但是,使用这些确切的方法意味着数据库不会使用以下代码进行升级

private static final int DB_Version = 2;

    public DbConnector(Context context){
        super(context, DB_Name, null, DB_Version);
        this.context = context;
    }

事实上,onUpgrade() 方法从未被调用:(

感谢任何帮助

【问题讨论】:

    标签: android database sqlite


    【解决方案1】:

    感谢 Joe Masilotti,这是答案 http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/comment-page-2/

    private static final int DATABASE_VERSION = 1;
    

    将构造函数更改为:

    public DataBaseHelper(Context context) {
        super(context, DB_NAME, null, DATABASE_VERSION);
        this.myContext = context;
    }
    

    createDataBase 更改为(感谢@kondortek):

    public void createDataBase() throws IOException {
        boolean dbExist = checkDataBase();
        if (dbExist) {
            Log.v(“DB Exists”, “db exists”);
            // By calling this method here onUpgrade will be called on a
            // writeable database, but only if the version number has been
            // bumped
            this.getWritableDatabase();
        }
        dbExist = checkDataBase();
        if (!dbExist) {
            // By calling this method and empty database will be created into
            // the default system path of your application so we are gonna be
            // able to overwrite that database with our database.
            this.getReadableDatabase();
            try {
                copyDataBase();
            } catch (IOException e) {
                throw new Error(“Error copying database”);
            }
        }
    }
    

    onUpgrade 更改为:

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (newVersion > oldVersion)
            Log.v(“Database Upgrade”, “Database version higher than old.”);
        myContext.deleteDatabase(DB_NAME);
    }
    

    【讨论】:

    • 为什么 dbExist 被调用两次?通过调用 boolean dbExist = checkDataBase();我们已经知道是否存在数据库。为什么我们不使用其他方法而不是再次调用相同的方法 -> dbExist = checkDataBase(); ?
    • 调用 copyDataBase();在 onUpgrade(...) 方法中(删除旧数据库后),因此您无需检查 dbExist = checkDataBase();第二次。
    猜你喜欢
    • 2012-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多