Externally generated SQLite database considered read-only by Android's SQLiteOpenHelper
I have an SQLite database that I have generated using the SQLite JDBC connector found here.
I have then copied this database to my Android phone's SD card, and attempted to open it, using an SQLiteOpenHelper. I get the following exceptions:
ERROR/SQLiteOpenHelper(7373): android.database.sqlite.SQLiteException: attempt to write a readonly database: BEGIN EXCLUSIVE;
ERROR/AndroidRuntime(7373): Caused by: android.database.sqlite.SQLiteException: Can't upgrade read-only database from version 0 to 1: /mnt/sdcard/4Trak/4Trak.db
This doesn't make any sense to me. Why is it a read-only database? I was able to write to it to generate it in the first place, and again when I realised I would need an android_metadata table, and added it using an SQLite 开发者_JAVA技巧browser.
Sqlite will only open databases from your applications database directory.
DB_PATH = "/data/data/"+ context.getPackageName() + "/databases/";
In order to read and write your database, my understanding is that you will need to copy your database to this location:
InputStream myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
In order to do this copy, you will first have to open a database at the eventual destination of your database file:
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
Let me know if you have any questions
This just occurred to me. I wrote a program that is in 'production' and on a device and has data in a SQLite DB.
I backed up this data in the form of SQL statements (through aSQLiteManager). On the emulator, I recreated this db.
Then I launched my program, which was expecting a DB of version 5. My first access of the program was through getReadableDatabase in a subclass of SQLiteOpenHelper.
And there, I got this exception : can't upgrade a read-only database from version 0 to 5.
I fixed it by replacing the open call by getWritableDatabase.
Now, it gets weird, because the SQLite helper called onCreate, which contained CREATE TABLE statements, while the tables were already there, so it resulted in another error. I had to comment out the whole onCreate.
精彩评论