1. 程式人生 > >android 資料庫更改資料庫位置【DbFlow示範】

android 資料庫更改資料庫位置【DbFlow示範】

    //初始化資料庫
    public static void initDB() {
        boolean premission = PermissionUtils.isPremission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (!premission) return;
        File file = CreatFileUtil.getRootFile(getApplication());
        FileDatabaseContext mSdDatabaseContext = new FileDatabaseContext(context, file, true);
        FlowManager.init(mSdDatabaseContext);
    }

    //重新載入資料庫
    public static void deleteDB() {
        File file = CreatFileUtil.getRootFile(getApplication());
        file.delete();
        FlowManager.destroy();// 釋放引用,才能重新建立表
        initDB();
    }
package com.jtv.operation.dao;

import android.content.Context;
import android.content.ContextWrapper;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.text.TextUtils;

import com.raizlabs.android.dbflow.config.FlowLog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * 支援資料庫任意地址
 * <p>
 * 支援使用打包的資料庫res/raw/initdb.db
 *
 * @author 更生
 * @version 2017年3月2日
 */
public class FileDatabaseContext extends ContextWrapper {
    private File file;
    private boolean isUseDefaultDB;
    private Context context;

    /**
     * @param base           上下文
     * @param file           檔案儲存目錄
     * @param isUseDefaultDB 是否使用raw/initdb.db檔案
     */
    public FileDatabaseContext(Context base, File file, boolean isUseDefaultDB) {
        super(base);
        this.file = file;
        this.context = base;
        this.isUseDefaultDB = isUseDefaultDB;
    }

    @Override
    public Context getApplicationContext() {
        return this;
    }

    @Override
    public File getDatabasePath(String name) {
        //攜帶資料庫
        if (isUseDefaultDB) {
            File tempFile = file;

            if (tempFile == null)
                tempFile = context.getDatabasePath(name).getParentFile();
            createInitDatabase(tempFile, name, context);
        }

        if (file == null)
            return context.getDatabasePath(name);

        // 判斷目錄是否存在,不存在則建立該目錄
        if (!file.exists())
            file.mkdirs();

        File addressFile = new File(file, name);
        if (addressFile == null)
            addressFile = context.getDatabasePath(name);
        return addressFile;
    }

    public boolean createInitDatabase(File toFile, String name, Context context) {
        String path = toFile.getAbsolutePath();
        if (TextUtils.isEmpty(path))
            return false;

        // 判斷資料檔案是否存在,不存在的話使用打包的資料檔案
        String toFileName = path + File.separator + name;

        File f = new File(toFileName);
        if (f == null || f.exists())
            return false;

        File dir = new File(path);
        if (dir == null) return false;
        if (!dir.exists())
            dir.mkdirs();
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            is = context.getResources().openRawResource(context.getResources().getIdentifier("initdb", "raw", context.getPackageName()));
            // 建立輸出流
            fos = new FileOutputStream(toFileName);
            // 將資料輸出
            byte[] buffer = new byte[8192];
            int count = 0;
            while ((count = is.read(buffer)) > 0) {
                fos.write(buffer, 0, count);
            }
            buffer = null;
        } catch (Exception ee) {
            FlowLog.log(FlowLog.Level.I, ee.toString());
        } finally {
            try {
                fos.close();
            } catch (Exception ee) {
            }
            try {
                is.close();
            } catch (Exception ee) {
            }
        }
        return true;
    }

    //過載這個方法,是用來開啟SD卡上的資料庫的,android 2.3及以下會呼叫這個方法。
    @Override
    public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory) {
        SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null);
        return result;
    }

    //Android 4.0會呼叫此方法獲取資料庫。
    @Override
    public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory,
                                               DatabaseErrorHandler errorHandler) {
        SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null);
        return result;
    }
}