-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDBHelper.java
More file actions
82 lines (70 loc) · 2.7 KB
/
DBHelper.java
File metadata and controls
82 lines (70 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.example.build.blockpuzzle;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
/**
* Created by jc317897 on 5/01/2017.
*/
public class DBHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "game.db";
static final String TABLE_NAME = "users";
static final String USERNAME_COL = "username";
static final String SCORE_COL = "score";
public DBHelper(Context context) {
super(context,DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String create_table = "create table " + TABLE_NAME + " ("
+ USERNAME_COL + " text primary key,"
+ SCORE_COL + " integer)";
db.execSQL(create_table);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE_NAME);
onCreate(db);
}
public boolean insertPlayer(String usr) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(USERNAME_COL, usr);
values.put(SCORE_COL, 0);
db.insert(TABLE_NAME, null, values);
return true;
}
public Cursor getPlayer(String usr) {
SQLiteDatabase db = this.getReadableDatabase();
String sqlstr = "select * from " + TABLE_NAME + " where "
+ USERNAME_COL + " = " + "'" + usr + "'";
Cursor cursor = db.rawQuery(sqlstr, null);
return cursor;
}
public boolean updatePlayer(String usr, int score){
SQLiteDatabase db = this.getWritableDatabase();
if(getPlayer(usr) == null){
return false;
}
ContentValues values = new ContentValues();
values.put(SCORE_COL, score);
db.update(TABLE_NAME, values, USERNAME_COL + " = ?", new String[]{usr});
return true;
}
public ArrayList<String> getAllPlayerNames()
{
ArrayList<String> array_list = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery( "select * from " + TABLE_NAME, null );
cursor.moveToFirst();
while(cursor.isAfterLast() == false){
array_list.add(cursor.getString(cursor.getColumnIndex(USERNAME_COL)));
cursor.moveToNext();
}
cursor.close();
return array_list;
}
}//end of DBHelper