How to Update Database changes to already Installed Application

北城以北 提交于 2019-12-11 10:47:15

问题


If I make any change to database like adding new column in my android application. and If I have already installed that on my phone. when I reinstall / update that application on mobile it doesn't update the database changes.

My database code is :

package com.screenmagic.smsmagicmobileapp;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


public class DatabaseHandler extends SQLiteOpenHelper {


private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Test";


public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
    Log.d(TAG, "onCreate OF DatabaseHandler");

    db.execSQL("DROP TABLE IF EXISTS history");
    String CREATE_SMS_HISTORY_TABLE = "CREATE TABLE  history("+
    "id INTEGER PRIMARY KEY AUTOINCREMENT, mobileNumber TEXT, smsText TEXT)";
    Log.d("Insert: ", "Table create query:: "+ CREATE_SMS_HISTORY_TABLE);
    db.execSQL(CREATE_SMS_HISTORY_TABLE);
    Log.d("Insert: ", "Table created ..");

}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS sms_history");
    onCreate(db);
}


}

回答1:


Just use the onUpgrade (as an override) method, and you can put your database upgrades there. this way, none of the existing data will be blown away when the application has already been installed.

And make sure you don't drop the table as you're currently doing on:

db.execSQL("DROP TABLE IF EXISTS sms_history");

See reference for the method here and a video on how to implement it here



来源:https://stackoverflow.com/questions/14235188/how-to-update-database-changes-to-already-installed-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!