-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathNotesDbAdapter.java
103 lines (77 loc) · 2.98 KB
/
NotesDbAdapter.java
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
92
93
94
95
96
97
98
99
100
101
102
103
package net.tapi.handynotes;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class NotesDbAdapter {
private final Context context;
public static final String KEY_ROWID = "_id";
public static final String KEY_BODY = "body";
private static final String TAG = "NotesDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_CREATE =
"create table notes (_id integer primary key, "
+ "body text not null);";
private static final String DATABASE_NAME = "data";
private static final String DATABASE_TABLE = "notes";
private static final int DATABASE_VERSION = 1;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
}
public NotesDbAdapter(Context c) {
this.context = c;
}
public NotesDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(context);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public long createNote(int wId, String body) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_ROWID, wId);
initialValues.put(KEY_BODY, body);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteNote(int wId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + wId, null) > 0;
}
public String showNoteText(int wId) throws SQLException {
String result = "";
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID, KEY_BODY}, KEY_ROWID + "=" + wId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
if (mCursor.getCount() > 0) {
result = mCursor.getString(mCursor.getColumnIndex(KEY_BODY));
}
mCursor.close();
}
return result;
}
public boolean updateNote(int wId, String body) {
ContentValues args = new ContentValues();
args.put(KEY_BODY, body);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + wId, null) > 0;
}
}