您好,登录后才能下订单哦!
使用:
在你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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。