初始安装时数据库版本为零

时间:2010-06-06 15:22:06

标签: android sqlite

我发布了一个带有初始数据库的应用程序(世界时间)。现在我想通过数据库升级来更新应用程序。

我已经在OnUpgrade()中添加了升级代码并检查了newVersion。但它没有在我当地的测试中被调用......

所以我输入debug语句来获取数据库版本,它是零。

知道它为什么没有被版本化?

以下是从我的Assets文件夹中复制数据库的代码......

    InputStream myInput = myContext.getAssets().open(DB_NAME);

    // Path to the just created empty db
    String outFileName = DB_PATH + DB_NAME;

    //Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    //transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
        myOutput.write(buffer, 0, length);
    }

    //Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

以下是我的构造函数,OnCreate()& OnUpgrade()

public DatabaseHelper(Context context) {

    super(context, DB_NAME, null, DB_VERSION);
    this.myContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if(oldVersion == 1 && newVersion == 2){
        String sql = "update statement...."; // i have a correct update statement here
        db.execSQL(sql);
    }

}

-
马赫什
http://android.maheshdixit.com

3 个答案:

答案 0 :(得分:1)

您不必手动检查数据库版本,如果正确完成,SQLite会为您执行此操作。

在你的SQLiteOpenHelper继承类中,在构造函数中,你应该传递DB_VERSION,如下所示:

public class DBHelper extends SQLiteOpenHelper {
    public static final String DB_NAME = "your_db_name";
    public static final int DB_VERSION = 2;

    public DBHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
                ...
        }
  ...
}

然后在你的onCreate()中执行create table和onUpgrade()执行升级所需的任何操作而不检查版本,只有当SQLite已经为你检查过这个方法时才会调用此方法。如果需要在onUpgrade()中运行代码,只需增加DB_VERSION变量。

答案 1 :(得分:0)

您应该有一个类是您的数据库适配器。它将具有类似于以下内容的行:

private static final String  DATABASE_NAME = "sr4.db";
private static final int    DATABASE_VERSION = 1;

要让应用程序识别数据库需要更新,您需要做的就是更改DATABASE_VERSION设置为的数字。

答案 2 :(得分:0)

我发现了问题......只有在调用getReadableDatabases或getWriteableDatabases()时才会调用OnCreate()和OnUpgrade。如果数据库存在,我就不会调用其中任何一个。我改为调用SQLLiteDatabase.openDatabase(),它不调用OnCreate或OnUpgrade()。

现在我明确地调用了getWriteableDatabases(),它调用了OnUpgrade()。

感谢您的所有回复......