-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDBManager.java
More file actions
91 lines (67 loc) · 1.87 KB
/
Copy pathDBManager.java
File metadata and controls
91 lines (67 loc) · 1.87 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
85
86
87
88
89
90
91
import java.util.concurrent.atomic.AtomicInteger;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* @author lixiaoqing
*/
public class DBManager {
private AtomicInteger databaseCounter = new AtomicInteger();
private static DBManager instance;
private static SQLiteOpenHelper helper;
private SQLiteDatabase writableDatabase;
private SQLiteDatabase readableDatabase;
public static synchronized DBManager getInstance(SQLiteOpenHelper helper) {
if (instance == null) {
DBManager.helper = helper;
instance = new DBManager();
}
return instance;
}
public SQLiteDatabase getWritableDatabase() {
return closeOrOpenDatabase(true,true);
}
public void closeWritableDatabase() {
closeOrOpenDatabase(false,true);
}
public SQLiteDatabase getReadableDatabase() {
return closeOrOpenDatabase(true, false);
}
public void closeReadableDatabase() {
closeOrOpenDatabase(false, false);
}
/**
* close or open writable database
* @param isOpen
* true:open, false:close
* @param isWrite
* true:write, false:read
* @return
*/
private synchronized SQLiteDatabase closeOrOpenDatabase(boolean isOpen, boolean isWrite) {
if (true == isOpen) {
databaseCounter.incrementAndGet();
if(true == isWrite){
if(null == writableDatabase){
writableDatabase = helper.getWritableDatabase();
}
return writableDatabase;
} else {
if(null == readableDatabase){
readableDatabase = helper.getReadableDatabase();
}
return readableDatabase;
}
} else {
if (databaseCounter.decrementAndGet() == 0) {
if(null != writableDatabase){
writableDatabase.close();
} else if(null != readableDatabase){
readableDatabase.close();
}
writableDatabase = null;
readableDatabase = null;
}
return null;
}
}
}