2011-05-30 78 views
1

我已经使用这个教程为了创建和填充我自己的Android的SQLite数据库。 http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications自己的SQLite数据库和onUpgrade

然而,使用这些精确的方法意味着数据库犯规用下面的代码升级

private static final int DB_Version = 2; 

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

其实方法onUpgrade()不会被调用:(任何帮助

感恩

回答

4

感谢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); 
} 
+1

为什么dbExist被调用了两次?通过调用boolean dbExist = checkDataBase();我们已经知道是否存在数据库。为什么我们不这样做,而不是再次调用相同的方法 - > dbExist = checkDataBase(); ? – 2012-10-25 12:00:28

+0

call copyDataBase();在onUpgrade(...)方法中(在删除旧的数据库之后),以便不需要检查dbExist = checkDataBase();第二次。 – selva 2013-02-13 05:36:38