您好,登錄后才能下訂單哦!
使用:
在你project項目的build.gradle配置如下:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
}
}
// 使用數據庫升級輔助GreenDaoUpgradeHelper時添加
allprojects {
repositories {
maven { url "https://jitpack.io" }
}
}
在你的modules 里app/build.gradle里配置如下:
apply plugin: 'org.greenrobot.greendao'
dependencies {
compile 'org.greenrobot:greendao:3.2.2'
// 使用數據庫加密時添加
compile 'net.zetetic:android-database-sqlcipher:3.5.6'
// 使用數據庫升級輔助GreenDaoUpgradeHelper時添加
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實體類,代碼如下:
@Entity
br/>?????然后新建Area實體類,代碼如下:
@Entity
br/>@Id
private String AreaName;
}
? ? ?最后,Build->Make Module 'app',即可自動生成DaoMaster、DaoSession、Area和AreaDao。此時Area實體類的代碼如下:@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;
}
}
? ? ?添加其他實體類的方法與Area一樣。需要注意的是,不要手動修改DaoMaster、DaoSession、bean和beanDao的代碼,因為每一次編譯項目,都會重新生成一次DaoMaster、DaoSession、bean和beanDao。如果修改的話,就會被覆蓋掉。
? ? ?為了便于數據的讀取和添加,新建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()); //獲取未加密的數據庫
}catch (Exception e){
e.printStackTrace();
}
}
return daoMaster;
}
/**
* 獲取DaoSession對象
*
* @param context
* @return
*/
public static DaoSession getDaoSession(Context context) {
if (daoSession == null) {
if (daoMaster == null) {
getDaoMaster(context);
}
daoSession = daoMaster.newSession();
}
return daoSession;
}
}
??????在讀寫數據庫之前,要添加讀寫權限:
<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("地區編碼:").append(areas.get(i).getAreaCode())
.append(",地區名稱:").append(areas.get(i).getAreaName()).append("\n");
}
textview.setText(stringBuilder);
}
}
? ? ?運行結果如下圖所示:
? ? ?
修改數據庫文件路徑:
? ? ?默認情況下,新創建的數據存儲在data的包名目錄下,設備如果不root的話,是無法查看SQLite數據庫文件的。而實際應用中,我們往往需要copy數據庫,或借用第三方工具查閱或編輯數據庫內容。此時我們可以通過重寫Context的getDatabasePath(String?name)、openOrCreateDatabase(String?name,?int?mode,?CursorFactory?factory)、openOrCreateDatabase(String?name,?int?mode,?CursorFactory?factory,?DatabaseErrorHandler?errorHandler)等三個方法來修改SQLite文件的存儲路徑。
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) {
/**
* 獲得數據庫路徑,如果不存在,則創建對象對象
*
* @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卡不存在,請加載SD卡");
return null;
} else {// 如果存在
// 獲取sd卡路徑
String dbDir = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
dbDir += "/Android";// 數據庫所在目錄
String dbPath = dbDir + "/" + name;// 數據庫路徑
// 判斷目錄是否存在,不存在則創建該目錄
File dirFile = new File(dbDir);
if (!dirFile.exists())
dirFile.mkdirs();
// 數據庫文件是否創建成功
boolean isFileCreateSuccess = false;
// 判斷文件是否存在,不存在則創建該文件
File dbFile = new File(dbPath);
if (!dbFile.exists()) {
try {
isFileCreateSuccess = dbFile.createNewFile();// 創建文件
} catch (IOException e) {
e.printStackTrace();
}
} else
isFileCreateSuccess = true;
// 返回數據庫文件對象
if (isFileCreateSuccess)
return dbFile;
else
return super.getDatabasePath(name);
}
}
/**
* 重載這個方法,是用來打開SD卡上的數據庫的,android 2.3及以下會調用這個方法。
*
* @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會調用此方法獲取數據庫。
*
* @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()); //獲取未加密的數據庫
}catch (Exception e){
e.printStackTrace();
}
}
return daoMaster;
}
/**
* 獲取DaoSession對象
*
* @param context
* @return
*/
public static DaoSession getDaoSession(Context context) {
if (daoSession == null) {
if (daoMaster == null) {
getDaoMaster(context);
}
daoSession = daoMaster.newSession();
}
return daoSession;
}
}
?????
版本升級更新
比如需要在實體類加一個字段 或者 改變字段屬性等 就需要版本更新來保存以前的數據了;
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);
//更改過的實體類(新增的不用加) 更新UserDao文件 可以添加多個 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;
}
/**
//mHelper = new DaoMaster.DevOpenHelper(this, "notes-db", null);
db = mHelper.getWritableDatabase();
// 注意:該數據庫連接屬于 DaoMaster,所以多個 Session 指的是相同的數據庫連接。
mDaoMaster = new DaoMaster(db);
mDaoSession = mDaoMaster.newSession();
}
public DaoSession getDaoSession() {
return mDaoSession;
}
public SQLiteDatabase getDb() {
return db;
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。