Question

Let's say that I have a SQLite database that I create in a separate program and include in the assets folder to be copied when the application starts (assuming it doesn't already exist). The database contains two columns, A and B. Let's say that A contains a list of locations (Paris, London, New York, etc-- things the user cannot edit) and B stores the amount of times the user has visited the respective location (which the user CAN edit from within the app).

Now let's say I managed to spell the name of a location wrong in my original database. I go into my SQLite browser, make a quick fix to that entry, save it, and replace the old DB file in my assets folder. How do I update column A in the database that has already been copied to reflect the changes I made to the now read-only database in the assets folder WITHOUT wiping the data they have stored?

My initial impression was to use onUpgrade, but I've seen people say it's just for updating the schema of a database. In this case, my schema hasn't changed, only some data within it...

Was it helpful?

Solution

onUpgrade is correct to use for what you need. I update both schema and static data during upgrades. My onUpgrade structured like so:

@Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        if (oldVersion < 211)
        {
            // In this version we transfer Log data into new date keeping format - just milliseconds, no string formatting
            db.execSQL("DROP TABLE IF EXISTS " + LogData.TABLE_NAME);
            db.execSQL(LogData.TABLE_CREATE_SQL);
            logInformation(db, "Application upgraded to 2.1.1 level and existing log data cleared from device.");
        }

        if (oldVersion < 212)
        {
        }

        if (oldVersion < 220)
        {
            db.execSQL("DROP TABLE IF EXISTS " + MailData.MAIL_TABLE_NAME);
        }
    }

OTHER TIPS

Lets start from the beginning.. When you open your database with constructor SQLiteOpenHelper it will get version information from you.

If the database doesn't exist it calls onCreate method. If the existing database's version is lower than yours it calls onUpgrade method.

Please read android documentation for more information.

So, you can insert your initial information in the onCreate method. And you can alter your table or insert some additional information to your tables in the onUpgrade method.

Hope it helps..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top