· 6 years ago · Apr 26, 2019, 07:10 AM
1package com.figielski.grzegorz.cwiczeniaandroid2019;
2
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;
9
10public class ScoresDbAdapter {
11 private static final String DEBUG_TAG = "SqLiteScoreManager";
12
13 private static final int DB_VERSION = 1;
14 private static final String DB_NAME = "scores.db";
15 public static String getDbScoresTable() {
16 return DB_SCORES_TABLE;
17 }
18 private static final String DB_SCORES_TABLE = "scores";
19
20 public static final String KEY_ID = "_id";
21 public static final String ID_OPTIONS = "INTEGER PRIMARY KEY AUTOINCREMENT";
22 public static final int ID_COLUMN = 0;
23 public static final String KEY_ID_ITEMS = "id_items";
24 public static final String ID_ITEMS_OPTIONS = "INTEGER NOT NULL";
25 public static final int ID_ITEMS_COLUMN = 1;
26
27 private static final String DB_CREATE_SCORES_TABLE =
28 "CREATE TABLE " + getDbScoresTable() + "( " +
29 KEY_ID + " " + ID_OPTIONS + ", " +
30 KEY_ID_ITEMS + " " + ID_ITEMS_OPTIONS +
31 ");";
32
33 private static final String DROP_SCORES_TABLE =
34 "DROP TABLE IF EXISTS " + getDbScoresTable();
35
36 private SQLiteDatabase db;
37 private Context context;
38 private DatabaseHelper dbHelper;
39
40 private static class DatabaseHelper extends SQLiteOpenHelper {
41 public DatabaseHelper(Context context, String name,
42 SQLiteDatabase.CursorFactory factory, int version) {
43 super(context, name, factory, version);
44 }
45
46 @Override
47 public void onCreate(SQLiteDatabase db) {
48 db.execSQL(DB_CREATE_SCORES_TABLE);
49
50 Log.d(DEBUG_TAG, "Database creating...");
51 Log.d(DEBUG_TAG, "Table " + DB_SCORES_TABLE + " ver." + DB_VERSION + " created");
52 }
53
54 @Override
55 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
56 db.execSQL(DROP_SCORES_TABLE);
57
58 Log.d(DEBUG_TAG, "Database updating...");
59 Log.d(DEBUG_TAG, "Table " + DB_SCORES_TABLE + " updated from ver." + oldVersion + " to ver." + newVersion);
60 Log.d(DEBUG_TAG, "All data is lost.");
61
62 onCreate(db);
63 }
64 }
65
66 public ScoresDbAdapter(Context context) {
67 this.context = context;
68 }
69
70 public ScoresDbAdapter open(){
71 dbHelper = new DatabaseHelper(context, DB_NAME, null, DB_VERSION);
72 //dbHelper.onCreate(null);
73 try {
74 db = dbHelper.getWritableDatabase();
75 } catch (SQLException e) {
76 db = dbHelper.getReadableDatabase();
77 }
78 return this;
79 }
80
81 public void close() {
82 dbHelper.close();
83 }
84
85 public Cursor getAllScores() {
86 String[] columns = {KEY_ID, KEY_ID_ITEMS};
87 return db.query(getDbScoresTable(), columns, null, null, null, null, null);
88 }
89}