j256 / ormlite-android

ORMLite Android functionality used in conjunction with ormlite-core
http://ormlite.com/
ISC License
1.59k stars 367 forks source link

set dataBase inSDCard and onUpgrade cannot perform? #75

Open klower1989 opened 7 years ago

klower1989 commented 7 years ago

When l set database in SDCard, the onUpgrade cannot perform, my code is: public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

// name of the database file for your application -- change to something
// appropriate for your app
private static final String DATABASE_NAME = "MYDB.db";

private static final String DATABASE_JOURNAL_NAME = DATABASE_NAME
        + "-journal";

// any time you make changes to your database objects, you may have to
// increase the database version
//遗留问题,当设置数据库的位置为SDCard时,如果需要更新数据库,如给Table增加一个字段,会导致更新失败,onUpgrade未
//执行,至今未找到解决办法,但是保存在默认位置没有这个问题
public static final int DATABASE_VERSION = 2;

// SDCard 路径
private static String DATABASE_PATH = Environment
        .getExternalStorageDirectory() + "/" + DATABASE_NAME;

private static String DATABASE_PATH_JOURN = Environment
        .getExternalStorageDirectory() + "/" + DATABASE_JOURNAL_NAME;

private Context mContext;

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    mContext = context;

    setDataBasePath();
}

private void setDataBasePath() {
    // 以下代码表示将DB文件存储到自己定义的目录下
    initDtaBasePath();
    try {
        File f = new File(DATABASE_PATH);
        if (!f.exists()) {
            SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(
                    DATABASE_PATH, null);
            onCreate(db);
            db.close();
        }
    } catch (Exception e) {
    }
}

// 判断SDCard是否存在
private void initDtaBasePath() {
    if (!ExistSDCard()) {
        DATABASE_PATH = mContext.getFilesDir().getAbsolutePath() + "/"
                + DATABASE_NAME;
        DATABASE_PATH_JOURN = mContext.getFilesDir().getAbsolutePath()
                + "/" + DATABASE_JOURNAL_NAME;
    }
}

public static boolean ExistSDCard() {
    if (Environment.getExternalStorageState().equals(
            Environment.MEDIA_MOUNTED)) {
        return true;
    } else
        return false;
}

 //以下2个方法表示把DB 文件存储到SDCard目录
@Override
public synchronized SQLiteDatabase getWritableDatabase() {
    return SQLiteDatabase.openDatabase(DATABASE_PATH, null,
            SQLiteDatabase.OPEN_READWRITE);
}

public synchronized SQLiteDatabase getReadableDatabase() {
    return SQLiteDatabase.openDatabase(DATABASE_PATH, null,
            SQLiteDatabase.OPEN_READONLY);
}

private ConnectionSource connectionSource = null;

@Override
public ConnectionSource getConnectionSource() {
    if (connectionSource == null) {
        connectionSource = super.getConnectionSource();
    }
    return connectionSource;

}

/**
 * This is called when the database is first created. Usually you should
 * call createTable statements here to create the tables that will store
 * your data.
 */
@Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
    Log.i(DatabaseHelper.class.getName(), "onCreate");
    try {
        TableUtils.createTable(connectionSource, UserInfo.class);
        TableUtils.createTable(connectionSource, AddressInfo.class);
    } catch (java.sql.SQLException e) {
        Log.e(DatabaseHelper.class.getName(), "Can't create database",
                e);
        throw new RuntimeException(e);
    }

}

@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    super.onDowngrade(db, oldVersion, newVersion);
}

/**
 * This is called when your application is upgraded and it has a higher
 * version number. This allows you to adjust the various data to match the
 * new version number.
 */
@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource,
                      int oldVersion, int newVersion) {
    Log.i(DatabaseHelper.class.getName(), "onUpgrade oldVersion: " + oldVersion + " newVersion:" + newVersion);
    // Upgrade to Version 2
    if (oldVersion < DATABASE_VERSION) {
        try {
            new UserInfoDao(mContext).getDao().executeRaw("ALTER TABLE `userinfo` ADD COLUMN country TEXT DEFAULT 'china';");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

public void deleteDB() {
    if (mContext != null) {
        File f = mContext.getDatabasePath(DATABASE_NAME);
        if (f.exists()) {
            // mContext.deleteDatabase(DATABASE_NAME);
            Log.e("DB", "---delete SDCard DB---");
            f.delete();
        } else {
            Log.e("DB", "---delete App DB---");
            mContext.deleteDatabase(DATABASE_NAME);
        }

        File file = mContext.getDatabasePath(DATABASE_PATH);
        if (file.exists()) {
            Log.e("DB", "---delete SDCard DB 222---");
            file.delete();
        }

        File file2 = mContext.getDatabasePath(DATABASE_PATH_JOURN);
        if (file2.exists()) {
            Log.e("DB", "---delete SDCard DB 333---");
            file2.delete();
        }
    }
}

/**
 * Close the database connections and clear any cached DAOs.
 */
@Override
public void close() {
    super.close();
}

}