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