DaoManager.java
2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package com.lijinji.scan.wmsgreendao;
import android.content.Context;
import org.greenrobot.greendao.query.QueryBuilder;
public class DaoManager {
private static final String DB_NAME = "wmsgreendao";
private static Context mContext;
//多线程中要被共享的使用volatile关键字修饰
private volatile static DaoManager manager = new DaoManager();
private static DaoMaster sDaoMaster;
private static DaoMaster.DevOpenHelper sHelper;
private static DaoSession sDaoSession;
/**
* 单例模式获得操作数据库对象
* @return
*/
public static DaoManager getInstance(Context context){
mContext = context;
return manager;
}
/**
* 判断是否有存在数据库,如果没有则创建
* @return
*/
public DaoMaster getDaoMaster(){
if(sDaoMaster == null) {
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(mContext, DB_NAME, null);
sDaoMaster = new DaoMaster(helper.getWritableDatabase());
}
return sDaoMaster;
}
/**
* 完成对数据库的添加、删除、修改、查询操作,仅仅是一个接口
* @return
*/
public DaoSession getDaoSession(){
if(sDaoSession == null){
if(sDaoMaster == null){
sDaoMaster = getDaoMaster();
}
sDaoSession = sDaoMaster.newSession();
}
return sDaoSession;
}
/**
* 打开输出日志,默认关闭
*/
public void setDebug(){
QueryBuilder.LOG_SQL = true;
QueryBuilder.LOG_VALUES = true;
}
/**
* 关闭所有的操作,数据库开启后,使用完毕要关闭
*/
public void closeConnection(){
closeHelper();
closeDaoSession();
}
public void closeHelper(){
if(sHelper != null){
sHelper.close();
sHelper = null;
}
}
public void closeDaoSession(){
if(sDaoSession != null){
sDaoSession.clear();
sDaoSession = null;
}
}
}