如何在更新android app时用新的数据库完全替换旧的sqlite数据库?

时间:2018-04-24 04:23:28

标签: android sqlite

我的应用版本1.0中包含带有离线数据存储的SQLite数据库。目的是用户可以搜索某些主题而无需互联网保持离线状态。现在在下一次更新中,我想将我的应用程序同步到Web服务,这样如果在Web服务上更新了新主题,那么我的应用程序会自动下载它们并存储在本地SQLite数据库中。对于这个新场景,我需要修改旧表以及想要创建一些新表。但是对于旧桌子我只想添加一些字段而不想丢失旧数据。所以现在我想,在我的下一次更新中,应用程序将删除以前的SQLite数据库并替换为这个新数据库。我读过this question但是被评论搞糊涂了,他们正在讨论删除旧表和创建新表。但在这种情况下,如何手动在新表中插入太多旧数据。

以下是我正在使用的DBHelper类:

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;
    }

以下是我的方法我从活动方法调用数据库:

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

1 个答案:

答案 0 :(得分:2)

尝试。

在SQLITEOpenHelper类

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.
    }

然后OverRide onUpgrade方法并执行

@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


}

希望这可以帮助您解决问题。使用现有数据库进行升级比创建新数据库更好。您可以使用逻辑进行升级。在升级数据库代码时,不要将onCreate代码更改为新代码。