· 8 years ago · Feb 26, 2018, 09:46 PM
1package com.example.pablo.infovalenciacf;
2
3import android.content.ContentValues;
4import android.content.Context;
5import android.database.Cursor;
6import android.database.sqlite.SQLiteDatabase;
7import android.database.sqlite.SQLiteOpenHelper;
8import android.util.Log;
9
10/**
11 * Created by pablo on 24/2/18.
12 */
13
14public class UsersDBHelper extends SQLiteOpenHelper {
15
16 public static final String TAG = UsersDBHelper.class.getSimpleName();
17 public static final String DB_NAME = "valencia.db";
18 public static final int DB_VERSION = 1;
19
20 public static final String USER_TABLE = "usuarios";
21 public static final String COLUMN_ID = "_id";
22 public static final String COLUMN_USER = "username";
23 public static final String COLUMN_EMAIL = "email";
24 public static final String COLUMN_PASS = "password";
25
26 public static final String sqlCreate = "CREATE TABLE " + USER_TABLE + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + COLUMN_USER + " TEXT," + COLUMN_EMAIL + " TEXT," + COLUMN_PASS + " TEXT)";
27
28 public UsersDBHelper(Context context) {
29 super(context, DB_NAME, null, DB_VERSION);
30 }
31
32 @Override
33 public void onCreate(SQLiteDatabase db) {
34 db.execSQL(sqlCreate);
35 }
36
37 @Override
38 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
39 db.execSQL("DROP TABLE IF EXISTS " + USER_TABLE);
40 onCreate(db);
41 }
42
43 public void addUser(String username, String email, String pass) {
44 SQLiteDatabase db = this.getWritableDatabase();
45
46 ContentValues values = new ContentValues();
47 values.put(COLUMN_USER, username);
48 values.put(COLUMN_EMAIL, email);
49 values.put(COLUMN_PASS, pass);
50
51 long id = db.insert(USER_TABLE, null, values);
52 db.close();
53
54 Log.d(TAG, "user inserted" + id);
55 }
56
57 public boolean getUser(String username, String pass) {
58 String selectQuery = "select * from " + USER_TABLE + " where " + COLUMN_USER + " = " + "'" + username + "'" + " and " + COLUMN_PASS + " = " + "'" + pass + "'";
59
60 SQLiteDatabase db = this.getReadableDatabase();
61 Cursor cursor = db.rawQuery(selectQuery, null);
62
63 cursor.moveToFirst();
64
65 if (cursor.getCount() > 0) {
66 return true;
67 }
68
69 cursor.close();
70 db.close();
71
72 return false;
73 }
74}