· 8 years ago · Jan 26, 2018, 07:08 PM
1public class DatabaseHandler extends SQLiteOpenHelper {
2
3 private static final String TAG = "DatabaseHandler";
4
5 private static final int DATABASE_VERSION = 4;
6 private static final String DATABASE_NAME = "notes_manager";
7 private static final String TABLE_NAME = "notes";
8
9 // Coloumn Names
10 private static final String KEY_ID = "id";
11 private static final String KEY_TITLE = "title";
12 private static final String KEY_NOTE = "note";
13
14 // Coloumn Combinations
15 private static final String[] COLS_ID_TITLE_NOTE = new String[] {KEY_ID,KEY_TITLE,KEY_NOTE};
16
17
18 public DatabaseHandler(Context context) {
19 super(context, DATABASE_NAME, null, DATABASE_VERSION);
20 }
21
22 @Override
23 public void onCreate(SQLiteDatabase db) {
24
25 String CREATE_NOTES_TABLE = "CREATE TABLE " + TABLE_NAME + " ( "
26 + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT"+", "
27 + KEY_TITLE + " TEXT NOT NULL"+ ", "
28 + KEY_NOTE + " TEXT"
29 + ")";
30
31 Log.d(TAG,CREATE_NOTES_TABLE);
32
33 db.execSQL(CREATE_NOTES_TABLE);
34
35 }
36
37 @Override
38 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
39
40 String DROP_TABLE = "DROP TABLE IF EXISTS "+ TABLE_NAME;
41
42 Log.d(TAG,DROP_TABLE);
43
44 db.execSQL(DROP_TABLE);
45
46 onCreate(db);
47
48 }
49
50 //CRUD OPERATIONS
51
52 public void addNote(Note note) {
53
54 SQLiteDatabase db = this.getWritableDatabase();
55
56 ContentValues values = new ContentValues();
57 values.put(KEY_TITLE, note.getTitle());
58 values.put(KEY_NOTE, note.getNote());
59
60
61 db.insert(TABLE_NAME,null,values);
62 db.close();
63 }
64
65 public Note getNote(int id){
66 SQLiteDatabase db = this.getReadableDatabase();
67
68 Cursor c = db.query(TABLE_NAME,COLS_ID_TITLE_NOTE,KEY_ID +"=?",new String[]{String.valueOf(id)},null,null,null,null);
69 if(c != null){
70 c.moveToFirst();
71 }
72 db.close();
73
74 Log.d(TAG,"Get Note Result "+ c.getString(0)+","+c.getString(1)+","+c.getString(2));
75 Note note = new Note(Integer.parseInt(c.getString(0)),c.getString(1),c.getString(2));
76 return note;
77 }
78
79 public List<Note> getAllNotes(){
80 SQLiteDatabase db = this.getReadableDatabase();
81
82 List<Note> noteList = new ArrayList<>();
83
84 Cursor cursor = db.query(TABLE_NAME,COLS_ID_TITLE_NOTE,null,null,null,null,null);
85
86
87 if(cursor!= null && cursor.moveToFirst()){
88
89 do{
90 Note note = new Note();
91 note.setId(Integer.parseInt(cursor.getString(0)));
92 note.setTitle(cursor.getString(1));
93 note.setNote(cursor.getString(2));
94 noteList.add(note);
95
96 }while (cursor.moveToNext());
97
98
99 }
100 db.close();
101 return noteList;
102
103 }
104
105
106
107
108
109}