· 9 years ago · Oct 21, 2016, 12:40 PM
1import android.content.ContentValues;
2import android.content.Context;
3import android.database.Cursor;
4import android.database.SQLException;
5import android.database.sqlite.SQLiteDatabase;
6
7public class LoginDataBaseAdapter {
8
9 public static final int NAME_COLUMN = 1;
10
11 // TODO: Create public field for each column in your table.
12 // SQL Statement to create a new database.
13 static final String DATABASE_CREATE = "create table IF NOT EXISTS" + "LOGIN" +
14 "( " + "USERNAME text primary key,PASSWORD text); ";
15
16
17 // Variable to hold the database instance
18 public SQLiteDatabase db;
19 // Context of the application using the database.
20 private final Context context;
21 // Database open/upgrade helper
22 private DataBaseHelper dbHelper;
23 //Constructor
24
25 public LoginDataBaseAdapter(Context _context) {
26 context = _context;
27 dbHelper = new DataBaseHelper(context);
28 }
29
30 public LoginDataBaseAdapter open() throws SQLException {
31 db = dbHelper.getWritableDatabase();
32 return this;
33 }
34
35 public void close() {
36 db.close();
37 }
38
39 public SQLiteDatabase getDatabaseInstance() {
40 return db;
41 }
42
43 public boolean insertEntry(String userName, String password) {
44 ContentValues newValues = new ContentValues();
45 // Assign values for each row.
46 newValues.put("USERNAME", userName);
47 newValues.put("PASSWORD", password);
48
49 // Insert the row into your table
50 if (db.insert("LOGIN", null, newValues) == -1) {
51 return false;
52 } else {
53 return true;
54 }
55 }
56
57
58 public int deleteEntry(String userName,String password) {
59 String storedPassword = getSinlgeEntry(userName);
60 if (password.equals(storedPassword)) {
61 String where = "USERNAME=?";
62 int numberOFEntriesDeleted = db.delete("LOGIN", where, new String[]{userName});
63 return numberOFEntriesDeleted;}
64 else {return 0;}
65 }
66
67
68 public String getSinlgeEntry(String userName) {
69 Cursor cursor = db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
70 if (cursor.getCount() < 1) // UserName Not Exist
71 {
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
82 public boolean updateEntry(String userName, String password, String newpass) {
83 // Define the updated row content.
84 String storedPassword = getSinlgeEntry(userName);
85 if (password.equals(storedPassword)) {
86 ContentValues updatedValues = new ContentValues();
87 // Assign values for each row.
88 updatedValues.put("USERNAME", userName);
89 updatedValues.put("PASSWORD", newpass);
90
91 db.update("LOGIN", updatedValues, "USERNAME=?", new String[]{userName});
92 return true;
93 }
94 else{return false;}
95 }
96}