· 8 years ago · Apr 07, 2018, 07:26 PM
1package com.example;
2
3import android.content.ContentValues;
4import android.content.Context;
5import android.database.Cursor;
6import android.database.SQLException;
7import android.database.sqlite.SQLiteDatabase;
8import android.database.sqlite.SQLiteOpenHelper;
9import android.util.Log;
10
11public class DBAdaptor
12{
13 public static final String KEY_ROWID = "id";
14 public static final String KEY_START = "start";
15 public static final String KEY_WORD = "word";
16 private static final String TAG = "DBAdaptor";
17
18 private static final String DATABASE_NAME = "example";
19 private static final String DATABASE_TABLE = "test";
20 private static final int DATABASE_VERSION = 1;
21 private SQLiteDatabase db;
22
23 private static final String DATABASE_CREATE =
24 "create table test (_id integer primary key autoincrement, "
25 + "start text not null, word text not null);";
26
27
28 private static class DatabaseHelper extends SQLiteOpenHelper
29 {
30 DatabaseHelper(Context context)
31 {
32 super(context, DATABASE_NAME, null, DATABASE_VERSION);
33 }
34
35 @Override
36 public void onCreate(SQLiteDatabase db)
37 {
38 //db = db1;
39 db.execSQL(DATABASE_CREATE);
40
41 }
42
43 @Override
44 public void onUpgrade(SQLiteDatabase db, int oldVersion,
45 int newVersion)
46 {
47 Log.w(TAG, "Upgrading database from version " + oldVersion
48 + " to "
49 + newVersion + ", which will destroy all old data");
50 db.execSQL("DROP TABLE IF EXISTS test");
51 onCreate(db);
52 }
53 }
54
55
56
57 private final Context context;
58
59 private DatabaseHelper DBHelper;
60
61
62 public DBAdaptor(Context ctx)
63 {
64 this.context = ctx;
65 //DBHelper = new DatabaseHelper(context);
66 }
67
68
69
70 //---opens the database---
71 public DBAdaptor open() throws SQLException
72 {
73 DBHelper = new DatabaseHelper(context);
74 db = DBHelper.getWritableDatabase();
75 return this;
76 }
77
78 //---closes the database---
79 public void close()
80 {
81 DBHelper.close();
82 }
83
84
85
86 //---retrieves a particular row based on startwith field---
87 public Cursor getWords(String start) throws SQLException
88 {
89 Cursor mCursor =
90 db.query(DATABASE_TABLE, new String[] {
91 KEY_WORD
92 },
93 KEY_START + " = " + start,
94 null,
95 null,
96 null,
97 null,
98 null);
99 if (mCursor != null) {
100 mCursor.moveToFirst();
101 }
102 return mCursor;
103 }
104
105}