溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Android 高效的SQLite型數(shù)據(jù)庫greenDAO使

發(fā)布時(shí)間:2020-07-16 08:52:22 來源:網(wǎng)絡(luò) 閱讀:255 作者:鷺明 欄目:移動(dòng)開發(fā)

使用:
在你project項(xiàng)目的build.gradle配置如下:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
}
}

// 使用數(shù)據(jù)庫升級(jí)輔助GreenDaoUpgradeHelper時(shí)添加
allprojects {
repositories {
maven { url "https://jitpack.io" }
}
}

在你的modules 里app/build.gradle里配置如下:

apply plugin: 'org.greenrobot.greendao'

dependencies {
compile 'org.greenrobot:greendao:3.2.2'

// 使用數(shù)據(jù)庫加密時(shí)添加
compile 'net.zetetic:android-database-sqlcipher:3.5.6'

// 使用數(shù)據(jù)庫升級(jí)輔助GreenDaoUpgradeHelper時(shí)添加
compile 'com.github.yuweiguocn:GreenDaoUpgradeHelper:v2.0.1'

}

greendao {
schemaVersion 1
daoPackage 'com.greendao.db
targetGenDir 'src/main/java'
}

? ? ?首先,新建datamodel包,用以包含DaoMaster、DaoSession、bean和beanDao等。?????然后新建Area實(shí)體類,代碼如下:
@Entity
br/>?????然后新建Area實(shí)體類,代碼如下:
@Entity
br/>@Id
private String AreaName;
}
? ? ?最后,Build->Make Module 'app',即可自動(dòng)生成DaoMaster、DaoSession、Area和AreaDao。此時(shí)Area實(shí)體類的代碼如下:@Entity
br/>@Entity
br/>@Id
private String AreaName;
@Generated(hash = 262290694)
public Area(String AreaCode, String AreaName) {
this.AreaCode = AreaCode;
this.AreaName = AreaName;
}
@Generated(hash = 179626505)
public Area() {
}
public String getAreaCode() {
return this.AreaCode;
}
public void setAreaCode(String AreaCode) {
this.AreaCode = AreaCode;
}
public String getAreaName() {
return this.AreaName;
}
public void setAreaName(String AreaName) {
this.AreaName = AreaName;
}
}
? ? ?添加其他實(shí)體類的方法與Area一樣。需要注意的是,不要手動(dòng)修改DaoMaster、DaoSession、bean和beanDao的代碼,因?yàn)槊恳淮尉幾g項(xiàng)目,都會(huì)重新生成一次DaoMaster、DaoSession、bean和beanDao。如果修改的話,就會(huì)被覆蓋掉。
? ? ?為了便于數(shù)據(jù)的讀取和添加,新建GreenDaoHelper輔助類,代碼如下:
public class GreenDaoHelper extends Application {
private GreenDaoHelper Instance;
private static DaoMaster daoMaster;
private static DaoSession daoSession;

public GreenDaoHelper getInstance() {
    if (Instance == null) {
        Instance = this;
    }
    return Instance;
}

/**
* 獲取DaoMaster
*
* @param context
* @return
*/
public static DaoMaster getDaoMaster(Context context) {
    if (daoMaster == null) {
        try{
            DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(context,"test.db",null);
            daoMaster = new DaoMaster(helper.getWritableDatabase()); //獲取未加密的數(shù)據(jù)庫
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    return daoMaster;
}

/**
* 獲取DaoSession對(duì)象
*
* @param context
* @return
*/
public static DaoSession getDaoSession(Context context) {

    if (daoSession == null) {
        if (daoMaster == null) {
            getDaoMaster(context);
        }
        daoSession = daoMaster.newSession();
    }
    return daoSession;
}

}
??????在讀寫數(shù)據(jù)庫之前,要添加讀寫權(quán)限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
?????在MainActivity.java中添加讀寫代碼:
public class MainActivity extends AppCompatActivity {

private TextView textview;
private DaoSession session;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textview=(TextView)findViewById(R.id.textview);

    session = GreenDaoHelper.getDaoSession(this);
    session.getAreaDao().deleteAll();//清空所有記錄

    //添加記錄
    Area area = new Area("01","北京");
    Area area1 = new Area("02","天津");
    session.getAreaDao().insert(area);
    session.getAreaDao().insert(area1);

    //查詢記錄
    StringBuilder stringBuilder = new StringBuilder();
    List<Area> areas = session.getAreaDao().loadAll();
    for (int i = 0,n = areas.size();i<n;++i){
        stringBuilder.append("地區(qū)編碼:").append(areas.get(i).getAreaCode())
                .append(",地區(qū)名稱:").append(areas.get(i).getAreaName()).append("\n");
    }

    textview.setText(stringBuilder);
}

}
? ? ?運(yùn)行結(jié)果如下圖所示:

? ? ?
修改數(shù)據(jù)庫文件路徑:
? ? ?默認(rèn)情況下,新創(chuàng)建的數(shù)據(jù)存儲(chǔ)在data的包名目錄下,設(shè)備如果不root的話,是無法查看SQLite數(shù)據(jù)庫文件的。而實(shí)際應(yīng)用中,我們往往需要copy數(shù)據(jù)庫,或借用第三方工具查閱或編輯數(shù)據(jù)庫內(nèi)容。此時(shí)我們可以通過重寫Context的getDatabasePath(String?name)、openOrCreateDatabase(String?name,?int?mode,?CursorFactory?factory)、openOrCreateDatabase(String?name,?int?mode,?CursorFactory?factory,?DatabaseErrorHandler?errorHandler)等三個(gè)方法來修改SQLite文件的存儲(chǔ)路徑。

public class GreenDaoHelper extends Application {
private GreenDaoHelper Instance;
private static DaoMaster daoMaster;
private static DaoSession daoSession;

public GreenDaoHelper getInstance() {
    if (Instance == null) {
        Instance = this;
    }
    return Instance;
}

/**
* 獲取DaoMaster
*
* @param context
* @return
*/
public static DaoMaster getDaoMaster(Context context) {

    if (daoMaster == null) {

        try{
            ContextWrapper wrapper = new ContextWrapper(context) {
            /**
            * 獲得數(shù)據(jù)庫路徑,如果不存在,則創(chuàng)建對(duì)象對(duì)象
            *
            * @param name
            */
            @Override
            public File getDatabasePath(String name) {
                // 判斷是否存在sd卡
                boolean sdExist = android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState());
                if (!sdExist) {// 如果不存在,
                    Log.e("SD卡管理:", "SD卡不存在,請(qǐng)加載SD卡");
                    return null;
                } else {// 如果存在
                    // 獲取sd卡路徑
                    String dbDir = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
                    dbDir += "/Android";// 數(shù)據(jù)庫所在目錄
                    String dbPath = dbDir + "/" + name;// 數(shù)據(jù)庫路徑
                    // 判斷目錄是否存在,不存在則創(chuàng)建該目錄
                    File dirFile = new File(dbDir);
                    if (!dirFile.exists())
                        dirFile.mkdirs();

                    // 數(shù)據(jù)庫文件是否創(chuàng)建成功
                    boolean isFileCreateSuccess = false;
                    // 判斷文件是否存在,不存在則創(chuàng)建該文件
                    File dbFile = new File(dbPath);
                    if (!dbFile.exists()) {
                        try {
                            isFileCreateSuccess = dbFile.createNewFile();// 創(chuàng)建文件
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else
                        isFileCreateSuccess = true;
                    // 返回?cái)?shù)據(jù)庫文件對(duì)象
                    if (isFileCreateSuccess)
                        return dbFile;
                    else
                        return super.getDatabasePath(name);
                }
            }

            /**
            * 重載這個(gè)方法,是用來打開SD卡上的數(shù)據(jù)庫的,android 2.3及以下會(huì)調(diào)用這個(gè)方法。
            *
            * @param name
            * @param mode
            * @param factory
            */
            @Override
            public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory) {
                return SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null);
            }

            /**
            * Android 4.0會(huì)調(diào)用此方法獲取數(shù)據(jù)庫。
            *
            * @see android.content.ContextWrapper#openOrCreateDatabase(java.lang.String,
            *      int,
            *      android.database.sqlite.SQLiteDatabase.CursorFactory,
            *      android.database.DatabaseErrorHandler)
            * @param name
            * @param mode
            * @param factory
            * @param errorHandler
            */
            @Override
            public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler) {
                return SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null);
            }
            };
            DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(wrapper,"test.db",null);
            daoMaster = new DaoMaster(helper.getWritableDatabase()); //獲取未加密的數(shù)據(jù)庫
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    return daoMaster;
}

/**
* 獲取DaoSession對(duì)象
*
* @param context
* @return
*/
public static DaoSession getDaoSession(Context context) {

    if (daoSession == null) {
        if (daoMaster == null) {
            getDaoMaster(context);
        }
        daoSession = daoMaster.newSession();
    }

    return daoSession;
}

}
?????

版本升級(jí)更新
比如需要在實(shí)體類加一個(gè)字段 或者 改變字段屬性等 就需要版本更新來保存以前的數(shù)據(jù)了;

public class Helper extends DaoMaster.OpenHelper{

private static DaoMaster daoMaster;
private static DaoSession daoSession;

public static final String DBNAME = "greendao.db";

public Helper(Context context){
    super(context,DBNAME,null);
}

@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
    super.onUpgrade(db, oldVersion, newVersion);
    Log.i("version", oldVersion + "---先前和更新之后的版本---" + newVersion);
    if (oldVersion < newVersion) {
        Log.i("version", oldVersion + "---先前和更新之后的版本---" + newVersion);
        MigrationHelper.getInstance().migrate(db, UserDao.class);
        //更改過的實(shí)體類(新增的不用加)   更新UserDao文件 可以添加多個(gè)  XXDao.class 文件

// MigrationHelper.getInstance().migrate(db, UserDao.class,XXDao.class);
}
}

/**
 * 取得DaoMaster
 *
 * @param context
 * @return
 */
public static DaoMaster getDaoMaster(Context context) {
    if (daoMaster == null) {
        DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(context,
                DBNAME, null);
        daoMaster = new DaoMaster(helper.getWritableDatabase());
    }
    return daoMaster;
}

/**
 * 取得DaoSession
 *
 * @param context
 * @return
 */
public static DaoSession getDaoSession(Context context) {
    if (daoSession == null) {
        if (daoMaster == null) {
            daoMaster = getDaoMaster(context);
        }
        daoSession = daoMaster.newSession();
    }
    return daoSession;
}

}

public class GreenApplication extends Application {
private DaoMaster.DevOpenHelper mHelper;
//private Helper mHelper;
private SQLiteDatabase db;
private DaoMaster mDaoMaster;
private DaoSession mDaoSession;
public static GreenApplication instances;
@Override public void onCreate() {
super.onCreate();
instances = this;
setDatabase();
}
public static GreenApplication getInstances(){
return instances;
}

/**

  • 設(shè)置greenDao
    */
    private void setDatabase() {
    // 通過 DaoMaster 的內(nèi)部類 DevOpenHelper,你可以得到一個(gè)便利的 SQLiteOpenHelper 對(duì)象。
    // 可能你已經(jīng)注意到了,你并不需要去編寫「CREATE TABLE」這樣的 SQL 語句,因?yàn)?greenDAO 已經(jīng)幫你做了。
    // 注意:默認(rèn)的 DaoMaster.DevOpenHelper 會(huì)在數(shù)據(jù)庫升級(jí)時(shí),刪除所有的表,意味著這將導(dǎo)致數(shù)據(jù)的丟失。
    // 所以,在正式的項(xiàng)目中,你還應(yīng)該做一層封裝,來實(shí)現(xiàn)數(shù)據(jù)庫的安全升級(jí)。
       mHelper = new Helper(new GreenDaoUtils(this));

  
//mHelper = new DaoMaster.DevOpenHelper(this, "notes-db", null);
db = mHelper.getWritableDatabase();
// 注意:該數(shù)據(jù)庫連接屬于 DaoMaster,所以多個(gè) Session 指的是相同的數(shù)據(jù)庫連接。
mDaoMaster = new DaoMaster(db);
mDaoSession = mDaoMaster.newSession();
}
public DaoSession getDaoSession() {
return mDaoSession;
}
public SQLiteDatabase getDb() {
return db;
}
}

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI