简体   繁体   中英

Updating my pre-populated SQLite database using onUpgrade()

I have been working on upgrading my pre populated SQLite database and cannot quite work out how to get onUpgrade to work. Please see below my code to copy across the database.

// MAIN MENU ON GAME LOAD UP
DB_PATH = getDatabasePath(DataBaseHelper.DB_NAME).toString();
DataBaseHelper myDbHelper = new DataBaseHelper(this);
myDbHelper = new DataBaseHelper(this);
try
{
    myDbHelper.createDataBase();
}
catch (IOException ioe)     
{
    throw new Error("Unable to create database");
}
myDbHelper.close();

// HELPER CLASS
public class DataBaseHelper extends SQLiteOpenHelper 
{
    private static final int DATABASE_VERSION = 1;

    public DataBaseHelper(Context context) 
    {
        super(context, DB_NAME, null, DATABASE_VERSION);
        this.myContext = context;
    }

    public void createDataBase() throws IOException
    {
        boolean dbExist = databaseExist();
        if(dbExist)
        {
            //database already exist
        }
        else
        {
            try 
            {
                copyDataBase();
            } 
            catch (IOException e) 
            {
                throw new Error("Error copying database");
            }
        }
    }

    @Override
    public void onCreate(SQLiteDatabase db) {}

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
    {
        switch (oldVersion)
        {
            case 1:
                db.execSQL("UPDATE MazeOnDraw SET posX=1, posY=2 WHERE rowid=5");
                break;
        }
    }
}

So I am not sure what I am doing wrong here however onUpgrade never seems to get called, I am incrementing the database version. Further to this can this process work with multiple databases as I may have 2 different databases (although this can be condensed into 1 if need be).

Finally, can the onUpgrade process be tested through ecplise debugging or must it be tested through the alpha versions on the developer console.

Please chagne DB_vERSION values to 2.. so DDMS can identify app have newer version of databasee for upgrade..

CHANGE

private static final int DATABASE_VERSION = 2;

super(context, DB_NAME, null, DATABASE_VERSION );

in this statement last argument is database version.. set it to 2 for new updated APK. so existing user can have newly added table Or Column.

on updated apk onUpgrade will call. and there you can copy database from asset. but than exisiting user will have loss of data.. so best option is to add table dynamically in database.

refer this answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM