简体   繁体   English

自己的SQLite数据库和onUpgrade

[英]Own SQLite Database and onUpgrade

I've used this tutorial in order to create and populate my own SQLite database for android.我使用本教程为 android 创建和填充我自己的 SQLite 数据库。 http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications

However, using these exact methods mean that the database doesnt upgrade with the following code但是,使用这些确切的方法意味着数据库不会使用以下代码升级

private static final int DB_Version = 2;

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

In fact the method onUpgrade() is never called:(事实上,onUpgrade() 方法从未被调用:(

Grateful for any help感谢任何帮助

Here is the answer thanks to Joe Masilotti on http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/comment-page-2/这是感谢 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;

Change the constructor to:将构造函数更改为:

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

Change the createDataBase to (thanks @kondortek):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”);
        }
    }
}

Change onUpgrade to: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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM