2

I'm working on an Android application. My app contains a local database, located in the /assests folder of the app. When the user installs the app, it copies the database in order to use it. Then the user can add items to it.

My question is if I will release an update for my app, will it clear the data(deleting the copied database), thus erasing the user's changes to the database(Because the app will copy the database from the assets folder again)?

Tofira
  • 1,634
  • 4
  • 27
  • 39

3 Answers3

0

That depends entirely on how you copy it. Do you always copy it without checking to see if it already exists? Then yes, it probably will. You really would have to show us some code though to be sure.

Chris Thompson
  • 35,167
  • 12
  • 80
  • 109
  • I actually do check if it already exists. My question is if updating the app deletes the existing database. Is it like uninstalling and reinstalling the app? – Tofira Apr 06 '11 at 05:20
0

You should override the onUpgrade method in the SQLiteOpenHelper:

     /*
     * (non-Javadoc)
     * 
     * @see
     * android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite
     * .SQLiteDatabase)
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        // CREATE TABLE teas (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT
        // NULL, brew_time INTEGER);
        String sql = "CREATE TABLE " + TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + NAME + " TEXT NOT NULL, " + BREW_TIME + " INTEGER" + ");";
        db.execSQL(sql);
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite
     * .SQLiteDatabase, int, int)
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }
Mark Mooibroek
  • 7,636
  • 3
  • 32
  • 53
0

No. If a user is updating an application (not uninstalling it - in that case it will be deleted) and a database already exists then Android will not just delete it (it could contain important information!).

Instead the onUpgrade method of your SQLiteOpenHelper will be called, and it is up to you to decide if you want to clear the data or preserve it.

Joseph Earl
  • 23,351
  • 11
  • 76
  • 89
  • Ok thanks, but my question is how do I preserve the data exactly? Is there a way to test it without actually upgrading? – Tofira Apr 06 '11 at 13:57
  • Sure, just put a `Log` statement or do a `SELECT` in the `onUpgrade` method of your SQLiteOpenHelper. As long as you don't change the database explicitly then it will be left as is. http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int) – Joseph Earl May 07 '11 at 21:13