我使用本教程: Tutorial Custom database
我从assets文件夹复制数据库并将其复制到我的设备(或模拟器)。一切都是正确的。我在DDMS透视图中看到了我的数据库。但是我想要升级我的数据库,所以我做了:
super(context, DB_NAME, null, 2); //changed version from 1 to 2
并修改onUpgrade方法:
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(newVersion > oldVersion){
this.myContext.deleteDatabase(DB_NAME);
try {
this.copyDataBase();
} catch (IOException e) {
e.printStackTrace();
}
}
}
但是在运行之后我的设备上仍然有旧版本的数据库。我如何删除旧版本的数据库并复制新的。 DB_NAME是我的数据库名称(格式,但不是路径),copyDataBase()是将数据库复制到设备的方法(并且它可以正常工作)。
我粘贴了我的所有代码:
public class DataBaseHelper extends SQLiteOpenHelper{
private static String DB_PATH = "/data/data/sitcom.quiz/databases/";
private static String DB_NAME = "sitcoms.sqlite";
private SQLiteDatabase myDataBase;
private final Context myContext;
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 4);
this.myContext = context;
}
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - database already exist
}else{
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException{
//Open your local db as the input stream
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();
}
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
@Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d("adas", "dasd");
if(newVersion > oldVersion){
String myPath = DB_PATH + DB_NAME;
this.myContext.deleteDatabase(myPath);
try {
this.copyDataBase();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
和我的活动:
DataBaseHelper myDbHelper = new DataBaseHelper(this);
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
谢谢,如果你能给我理由或只是暗示为什么这不起作用。
答案 0 :(得分:5)
当调用函数onUpgrade()时,android已经打开了db。我不认为此时可以删除它。查看日志以获取更多信息。如果你想这样做,你需要将删除和复制代码移动到数据库尚未打开的地方。
答案 1 :(得分:2)
试试这段代码......我认为它可以解决您的问题。
public void onUpgrade(SQLiteDatabase database, int oldVersion,
int newVersion) {
Log.w(DatabaseHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS " + DATABASE_NAME);
onCreate(database);
}
答案 2 :(得分:1)
从资产复制数据库时,默认情况下版本为0。
在从资产中复制数据库的方法中,使用方法setVersion(int version)
为数据库对象设置其版本。
如果db存在,则在数据库对象上按方法getVersion()
检查其版本。现在自己处理它的onUpgrade,即如果db evrsion已经更新了noe,那么升级数据库然后setVersion(int new dbVersion)
。
答案 3 :(得分:0)
您可以在升级数据库之前删除旧的Db。
if(dbExist){
Log.v("com.db","db exists");
myContext.deleteDatabase(DB_NAME);`enter code here`
//openDataBase();
//do nothing - database already exist
}else{
Log.v("com.db","dbnot exists");
//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();
}
答案 4 :(得分:0)
只是补充:
在createDataBase()中有以下检查;
this.getReadableDatabase();
这将检查是否已存在具有所提供名称的数据库,如果没有,则创建一个空数据库,以便可以使用assets文件夹中的数据库覆盖该数据库。在较新的设备上,这可以完美地工作,但有一些设备无法正常工作。主要是旧设备。我不确切知道为什么,但似乎getReadableDatabase()函数不仅获取数据库而且还打开它。如果您随后从assets文件夹复制数据库,它仍然具有指向空数据库的指针,您将获得表不存在错误。
因此,为了使其适用于所有设备,您应该将其修改为以下几行:
SQLiteDatabase db = this.getReadableDatabase();
if (db.isOpen()){
db.close();
}
即使数据库在支票中被打开,它也会在此后关闭,它不会给您带来任何麻烦。
答案 5 :(得分:0)
主要思想是,每当您创建新数据库时,都应使用 SharedPreferences 来存储数据库版本。
之后,在创建数据库时,必须检查数据库是否具有新版本,然后删除旧数据库并创建新数据库
这段代码与我合作
private static class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "database.name";
private static final int DATABASE_VERSION = 1;
private static final String KEY_DB_VER = "database_version";
private final Context mContext;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mContext = context;
initialize();
}
/**
* Initializes database. Creates database if doesn't exist.
*/
private void initialize() {
if (databaseExists()) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(mContext);
int dbVersion = prefs.getInt(KEY_DB_VER, 1);
//
if (DATABASE_VERSION != dbVersion) {
File dbFile = mContext.getDatabasePath(DATABASE_NAME);
// delete the old databse
if (!dbFile.delete()) {
Log.w(TAG, "Unable to update database");
}
}
}
// create database if needed
if (!databaseExists()) {
createDatabase();
}
}
/**
* Returns true if database file exists, false otherwise.
* @return
*/
private boolean databaseExists() {
File dbFile = mContext.getDatabasePath(DATABASE_NAME);
return dbFile.exists();
}
public void createDataBase() throws IOException {
// If database not exists copy it from the assets
boolean mDataBaseExist = databaseExists();
if (!mDataBaseExist) {
this.getReadableDatabase();
this.close();
try {
// Copy the database from assests
copyDataBase();
//**save the database version by SharedPreferences**
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(KEY_DB_VER, DATABASE_VERSION);
editor.commit();
Log.e(TAG, "createDatabase database created");
} catch (IOException mIOException) {
throw new Error("ErrorCopyingDataBase");
}
}
}
// Copy the database from assets
private void copyDataBase() throws IOException {
Log.i("TAG", "copy database");
InputStream mInput = mContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream mOutput = new FileOutputStream(outFileName);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer)) > 0) {
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
mOutput.close();
mInput.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
}
}