· 8 years ago · Jun 03, 2018, 04:32 PM
1
2import android.content.ContentValues;
3import android.content.Context;
4import android.database.Cursor;
5import android.database.SQLException;
6import android.database.sqlite.SQLiteDatabase;
7import android.database.sqlite.SQLiteOpenHelper;
8import android.util.Log;
9import android.view.View;
10
11public class DBAdapter {
12 static final String KEY_ROWID = "_id";
13 static final String KEY_EMOTION = "emotion";
14 static final String KEY_X = "x";
15 static final String KEY_Y = "y";
16 static final String TAG = "DBAdapter1";
17 static final String DATABASE_NAME = "MyDB";
18 static final String DATABASE_TABLE = "emotions";
19 static final int DATABASE_VERSION = 1;
20 static final String DATABASE_CREATE =
21 "create table emotions (_id integer primary key autoincrement, "
22 + "emotion text not null, x integer not null, y integer not null);";
23 final Context context;
24 DatabaseHelper DBHelper;
25 SQLiteDatabase db;
26 public DBAdapter(Context ctx){
27 this.context = ctx;
28 DBHelper = new DatabaseHelper(context);
29 }
30 private static class DatabaseHelper extends SQLiteOpenHelper
31 {
32 DatabaseHelper(Context context)
33 {
34 super(context, DATABASE_NAME, null, DATABASE_VERSION);
35 } @Override public void onCreate(SQLiteDatabase db)
36 { try {
37 db.execSQL(DATABASE_CREATE);
38 } catch (SQLException e) {
39 e.printStackTrace();
40 }
41 }
42 @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
43 {
44 Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
45 + newVersion + ", which will destroy all old data");
46 db.execSQL("DROP TABLE IF EXISTS contacts");
47 onCreate(db); } } //---opens the database--
48 public DBAdapter open() throws SQLException
49 { db = DBHelper.getWritableDatabase();
50 return this; } //---closes the database--
51 public void close()
52 { DBHelper.close(); } //---insert a contact into the database--
53 public long insertEmotion(String emotion, String x,String y)
54 {
55 ContentValues initialValues = new ContentValues();
56 initialValues.put(KEY_EMOTION, emotion);
57 initialValues.put(KEY_X, x);
58 initialValues.put(KEY_Y, y);
59 return db.insert(DATABASE_TABLE, null, initialValues);
60 }
61 //---deletes a particular contact--
62 // ---retrieves all the contacts--
63 public Cursor getAllEmotions()
64 {
65 return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_EMOTION,KEY_X,KEY_Y},
66 null, null, null, null, null);
67 }
68 //---retrieves a particular contact--
69 public Cursor getEmotion(String emotion1) throws SQLException
70 {
71 Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {KEY_X, KEY_Y},
72 KEY_EMOTION + "=" + emotion1, null,null, null, null, null);
73 if (mCursor != null) { mCursor.moveToFirst();}
74 return mCursor;
75 }
76
77}