I have followed the many tutorials online on how to achieve copying a DB file from the "assets" folder in the apk to the "/data/data//databases" folder of the application. With my code it fails on the first time of opening it and copying the database over.
Like the tutorials say it creates an empty database in which my database is copied into, but it doesn't seem to work for me. The code is exactly the same as everywhere else. But here it is anyway with the appropriate Logs.
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
SQLiteDatabase db_Read = null;
if(dbExist){
//do nothing - database already exist
Log.v("DBHandler", "Database does exist");
}else{
//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.
Log.v("DBHandler", "Database does not exist");
db_Read = this.getReadableDatabase();
db_Read.close();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("error copying database"); //Error gets thrown here
}
}
}
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[] buff开发者_如何学编程er = 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();
}
I get the following error in the Log:
08-01 14:34:25.046: ERROR/Database(27530): sqlite3_open_v2("/data/data/com.package/databases/DB.sqlite", &handle, 1, NULL) failed
I am pretty certain the error is in the copying of the database over. if any more information is needed i'll gladly provide it.
EDIT: I am sure the error is in the copying of the database, all the path directories are correct. I think it has something to do with the line: InputStream myInput = myContext.getAssets().open(DB_NAME);
with maybe the context passed through being wrong, but I can't see how.
You copy database using regular file operations while error message clearly refers to sqlite
. So the error most likely occurs when you try to open non existing database. If there is a stack trace it will show exactly where it happens.
Finally, I recommend that you don't use class Error
as it's reserved for VM errors. Use RuntimeException
and always include root cause in it.
精彩评论