· 10 years ago · Sep 23, 2016, 12:48 PM
1package com.example.dep.unipiinformaticsapp;
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 DatabaseClass extends SQLiteOpenHelper {
12
13 public static final String DATABASE_NAME = "unipi.db";
14 public static final int DATABASE_VERSION = 1;
15 public static final String TABLE_NAME = "credentials";
16 public static final String COL_1 = "username";
17 public static final String COL_2 = "password";
18
19 public SQLiteDatabase db;
20 private final Context context;
21
22 public DatabaseClass(Context context) {
23 // context: use to open or create the database
24 super(context, DATABASE_NAME, null, DATABASE_VERSION);
25 this.context = context;
26 }
27
28 @Override
29 public void onCreate(SQLiteDatabase db) {
30 //db = this.getWritableDatabase();
31 db.execSQL("CREATE TABLE " + TABLE_NAME +" (USERNAME TEXT PRIMARY KEY,PASSWORD TEXT)");
32 }
33
34 @Override
35 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
36 Log.w("DB", "Upgrading from version " + oldVersion + " to " + newVersion);
37 db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
38 onCreate(db);
39 }
40
41 public DatabaseClass open() throws SQLException {
42 Log.w("DB", "Database opened");
43 db = this.getWritableDatabase();
44 return this;
45 }
46
47 public void close() {
48 Log.w("DB", "Database closed");
49 db.close();
50 }
51
52 public SQLiteDatabase getDatabaseInstance() {
53 return db;
54 }
55
56 public void insertEntry(String userName, String password) {
57 ContentValues newValues = new ContentValues();
58 newValues.put("USERNAME", userName);
59 newValues.put("PASSWORD", password);
60 Log.w("DB", newValues + " inserted");
61 db.insert(TABLE_NAME, null, newValues);
62 }
63
64 public int deleteEntry(String username) {
65 Log.w("DB", username + " deleted");
66 return db.delete(TABLE_NAME, "USERNAME=?", new String[] {username});
67 }
68
69 public String getSinlgeEntry(String username) {
70 Cursor cursor = db.query(TABLE_NAME, null, " USERNAME=?", new String[] {username}, null, null, null);
71 if (cursor.getCount() < 1) {
72 cursor.close();
73 return "NOT EXIST";
74 }
75 cursor.moveToFirst();
76 String password = cursor.getString(cursor.getColumnIndex("PASSWORD"));
77 cursor.close();
78 return password;
79 }
80
81 public void updateEntry(String username, String password) {
82 Log.w("DB", "Entry Updated");
83 ContentValues updatedValues = new ContentValues();
84 updatedValues.put("USERNAME", username);
85 updatedValues.put("PASSWORD", password);
86 db.update(TABLE_NAME, updatedValues, "USERNAME=?", new String[] { username });
87 }
88
89}