简体   繁体   中英

How do I completely replace the old sqlite database with new one on update of android app?

My app version 1.0 had the SQLite database with offline data store in it. The purpose is user can search some topics without internet staying offline. Now in next update I thought to sync my application to web service so that if new topics updated on web service then my app automatically download them and store in local SQLite database. For this new scenario, I need to modify the old tables as well as want to create some new tables. But for old tables I just want to add some fields and don't want to lose my old data. So now I want, on my next update, app will delete the previous SQLite database and replace with this new one. I read this question but got confused by comments as well as they are talking about deleting old tables and creating new tables. But in this case how can insert my too much old data in new tables manually.

Below is my DBHelper class I am using:

public class DBHelper extends SQLiteOpenHelper {

    public static String DB_PATH = "/data/data/com.example.myapp/databases/";
    public static String DB_NAME = "myapp.db";
    public static final int DB_VERSION = 1;

    public static final String TB_TOPICS = "My_Topics";

    private SQLiteDatabase myDB;
    private Context context;

    public DBHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }

    @Override
    public synchronized void close(){
        if(myDB!=null){
            myDB.close();
        }
        super.close();
    }

    /***
     * Open database
     * @throws SQLException
     */
    public void openDataBase() throws SQLException{
        String myPath = DB_PATH + DB_NAME;
        myDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
    }

    /***
     * Copy database from source code assets to device
     * @throws IOException
     */
    public void copyDataBase() throws IOException{
        try {
            InputStream myInput = context.getAssets().open(DB_NAME);
            String outputFileName = DB_PATH + DB_NAME;
            OutputStream myOutput = new FileOutputStream(outputFileName);

            byte[] buffer = new byte[1024];
            int length;

            while((length = myInput.read(buffer))>0){
                myOutput.write(buffer, 0, length);
            }

            myOutput.flush();
            myOutput.close();
            myInput.close();
        } catch (Exception e) {
            Log.e("tle99 - copyDatabase", e.getMessage());
        }

    }

    /***
     * Check if the database doesn't exist on device, create new one
     * @throws IOException
     */
    public void createDataBase() throws IOException {
        boolean dbExist = checkDataBase();

        if (dbExist) {

        } else {
            this.getReadableDatabase();
            try {
                copyDataBase();
            } catch (IOException e) {
                Log.e("tle99 - create", e.getMessage());
            }
        }
    }

    // ---------------------------------------------
    // PRIVATE METHODS
    // ---------------------------------------------

    /***
     * Check if the database is exist on device or not
     * @return
     */
    private boolean checkDataBase() {
        SQLiteDatabase tempDB = null;
        try {
            String myPath = DB_PATH + DB_NAME;
            tempDB = SQLiteDatabase.openDatabase(myPath, null,
                    SQLiteDatabase.OPEN_READWRITE);
        } catch (SQLiteException e) {
            Log.e("tle99 - check", e.getMessage());
        }
        if (tempDB != null)
            tempDB.close();
        return tempDB != null ? true : false;
    }

And Below is my method I am calling database from activity method:

List<AVData> listAVData = new ArrayList<AVData>();
    DBHelper dbHelper = new DBHelper(this);
    try {
        dbHelper.createDataBase();
    } catch (IOException e) {
        e.printStackTrace();
    }
    listAVData = dbHelper.getHeadings(topicToSearch.trim());

Try.

In SQLITEOpenHelper Class

public class YourHelperClassName extends SQLiteOpenHelper {

    public YourHelperClassName(Context c) {
            super(c, "YOUR_DBNAME", null, new_version_number);
        }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //Add the Table creation code for new version here. Since this code works for the new user or when the user cleare data from settings.
    }

Then OverRide onUpgrade method in it and do

@Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (oldVersion == your_old-version_number && newVersion == new_version_number) {

     //1.Fetch Data from old table and Assign it in a Cursor.
     //2.Drop the table and Create New Table or Alter the Table.
     //3.Add data to the new table from the Cursor.
     // If you are Altering the table it is not required to add the data again to the table


}

Hope this may help you to solve your problem. Its better to to do upgrade with the existing database than creating new. You can use your logic to upgrade. Dont for to change the onCreate code to the new code while upgrading the DB code.

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