Externally generated SQLite database considered read-only by Android's SQLiteOpenHelper

前端 未结 2 1925
孤独总比滥情好
孤独总比滥情好 2021-01-07 13:38

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 atte

相关标签:
2条回答
  • 2021-01-07 14:25

    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

    0 讨论(0)
  • 2021-01-07 14:35

    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.

    0 讨论(0)
提交回复
热议问题