2015-05-10 8 views
1

Я новичок в базе данных Android и SQLite. Я работаю над учебником, но мне трудно адаптировать его к моему приложению.Android Получить значения из базы данных SQLite

Я хочу создать базу данных высокого балла с высокой оценкой для каждого уровня. Итак, моя таблица будет называться HighScore и идентификаторы полей, уровня и HighScore. Уровень и HighScore - это целые числа.

Вот мои классы:

public class HighScore { 
 

 
    private int id; 
 
    private Integer Level; 
 
    private Integer highscore; 
 

 
    public HighScore(){} 
 

 
    public HighScore(Integer Level, Integer highscore) { 
 
     super(); 
 
     this.Level = Level; 
 
     this.highscore = highscore; 
 
    } 
 

 
    //getters & setters 
 

 
    
 
    public Integer getHighScore() { 
 
     return highscore; 
 
    } 
 

 
    public Integer getLevel() { 
 
     return Level; 
 
    } 
 

 
    public int getId() { 
 
     return id; 
 
    } 
 

 
    public void setId(int id) { 
 
     this.id = id; 
 
    } 
 

 
    public void setLevel(Integer Level) { 
 
     this.Level = Level; 
 
    } 
 

 
    public void setHighScore(Integer highscore) { 
 
     this.highscore = highscore; 
 
    } 
 
}

import java.util.LinkedList; 
 
import java.util.List; 
 

 
import android.content.ContentValues; 
 
import android.content.Context; 
 
import android.database.Cursor; 
 
import android.database.sqlite.SQLiteDatabase; 
 
import android.database.sqlite.SQLiteOpenHelper; 
 
import android.util.Log; 
 

 
public class MySQLiteHelper extends SQLiteOpenHelper { 
 

 
    // Database Version 
 
    private static final int DATABASE_VERSION = 1; 
 
    // Database Name 
 
    private static final String DATABASE_NAME = "HighScore"; 
 

 
    public MySQLiteHelper(Context context) { 
 
     super(context, DATABASE_NAME, null, DATABASE_VERSION); 
 
    } 
 

 
    @Override 
 
    public void onCreate(SQLiteDatabase db) { 
 
     // SQL statement to create HighScores table 
 
     String CREATE_HighScore_TABLE = "CREATE TABLE HighScores (" + 
 
       "id INTEGER PRIMARY KEY AUTOINCREMENT, " + 
 
       "Level INTEGER, "+ 
 
       "HIGHSCORE INTEGER)"; 
 

 
     // create HighScores table 
 
     db.execSQL(CREATE_HighScore_TABLE); 
 
    } 
 

 
    @Override 
 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
 
     // Drop older HighScores table if existed 
 
     db.execSQL("DROP TABLE IF EXISTS HighScores"); 
 

 
     // create fresh books table 
 
     this.onCreate(db); 
 
    } 
 
    //--------------------------------------------------------------------- 
 

 
    /** 
 
    * CRUD operations (create "add", read "get", update, delete) book + get all books + delete all books 
 
    */ 
 

 
    // HighScores table name 
 
    private static final String TABLE_HIGHSCORES = "HighScores"; 
 

 
    // HighScores Table Columns names 
 
    private static final String KEY_ID = "id"; 
 
    private static final String KEY_LEVEL = "Level"; 
 
    private static final String KEY_HIGHSCORE = "HIGHSCORE"; 
 

 
    private static final String[] COLUMNS = {KEY_ID,KEY_LEVEL,KEY_HIGHSCORE}; 
 

 
    public void addHighScore(HighScore highScore){ 
 
     Log.d("addHighScore", highScore.toString()); 
 
     // 1. get reference to writable DB 
 
     SQLiteDatabase db = this.getWritableDatabase(); 
 

 
     // 2. create ContentValues to add key "column"/value 
 
     ContentValues values = new ContentValues(); 
 
     values.put(KEY_LEVEL, highScore.getLevel()); // get title 
 
     values.put(KEY_HIGHSCORE, highScore.getHighScore()); // get author 
 

 
     // 3. insert 
 
     db.insert(TABLE_HIGHSCORES, // table 
 
       null, //nullColumnHack 
 
       values); // key/value -> keys = column names/ values = column values 
 

 
     // 4. close 
 
     db.close(); 
 
    } 
 

 
    public HighScore getHighScore(Integer Level){ 
 

 
     // 1. get reference to readable DB 
 
     SQLiteDatabase db = this.getReadableDatabase(); 
 

 
     // 2. build query 
 
     Cursor cursor = 
 
       db.query(TABLE_HIGHSCORES, // a. table 
 
         COLUMNS, // b. column names 
 
         " Level = ?", // c. selections 
 
         new String[] { String.valueOf(Level) }, // d. selections args 
 
         null, // e. group by 
 
         null, // f. having 
 
         null, // g. order by 
 
         null); // h. limit 
 

 
     // 3. if we got results get the first one 
 
     if (cursor != null) 
 
      cursor.moveToFirst(); 
 

 
     // 4. build highScore object 
 
     HighScore highScore = new HighScore(); 
 
     //highScore.setId(Integer.parseInt(cursor.getString(0))); 
 
     //highScore.setLevel(cursor.getInt(1)); 
 
     highScore.setHighScore(cursor.getInt(2)); 
 

 
     Log.d("getHighScore("+Level+")", highScore.toString()); 
 

 
     // 5. return highScore 
 
     return highScore; 
 
    } 
 

 
    // Get All HighScores 
 
    public List<HighScore> getAllHighScores() { 
 
     List<HighScore> highScores = new LinkedList<HighScore>(); 
 

 
     // 1. build the query 
 
     String query = "SELECT * FROM " + TABLE_HIGHSCORES; 
 

 
     // 2. get reference to writable DB 
 
     SQLiteDatabase db = this.getWritableDatabase(); 
 
     Cursor cursor = db.rawQuery(query, null); 
 

 
     // 3. go over each row, build highScore and add it to list 
 
     HighScore highScore = null; 
 
     if (cursor.moveToFirst()) { 
 
      do { 
 
       highScore = new HighScore(); 
 
       highScore.setId(Integer.parseInt(cursor.getString(0))); 
 
       highScore.setLevel(cursor.getInt(1)); 
 
       highScore.setHighScore(cursor.getInt(2)); 
 

 
       // Add highScore to highScores 
 
       highScores.add(highScore); 
 
      } while (cursor.moveToNext()); 
 
     } 
 

 
     Log.d("getAllHighScores()", highScores.toString()); 
 

 
     // return highScores 
 
     return highScores; 
 
    } 
 

 
    // Updating single highScore 
 
    public int updateHighScore(HighScore highScore) { 
 

 
     // 1. get reference to writable DB 
 
     SQLiteDatabase db = this.getWritableDatabase(); 
 

 
     // 2. create ContentValues to add key "column"/value 
 
     ContentValues values = new ContentValues(); 
 
     values.put("Level", highScore.getLevel()); // get title 
 
     values.put("HighScore", highScore.getHighScore()); // get author 
 

 
     // 3. updating row 
 
     int i = db.update(TABLE_HIGHSCORES, //table 
 
       values, // column/value 
 
       KEY_ID+" = ?", // selections 
 
       new String[] { String.valueOf(highScore.getId()) }); //selection args 
 

 
     // 4. close 
 
     db.close(); 
 

 
     return i; 
 

 
    } 
 

 
    // Deleting single highScore 
 
    public void deleteHighScore(HighScore highScore) { 
 

 
     // 1. get reference to writable DB 
 
     SQLiteDatabase db = this.getWritableDatabase(); 
 

 
     // 2. delete 
 
     db.delete(TABLE_HIGHSCORES, 
 
       KEY_ID+" = ?", 
 
       new String[] { String.valueOf(highScore.getId()) }); 
 

 
     // 3. close 
 
     db.close(); 
 

 
     Log.d("deleteHighScore", highScore.toString()); 
 

 
    } 
 
}

А потом в моей SetStartupValues ​​моего основного класса, у меня есть этот код:

 MySQLiteHelper db = new MySQLiteHelper(this); 
 
     intHighScore = db.getHighScore(intLevel);

То, что я хотел бы сделать это, когда работает метод SetStartUpValues, я могу получить высокий балл из таблицы для пользователей intLevel. Но intHighScore является целым числом, а метод getHighScore возвращает объект HighScore. Как я могу получить 1 значение поля из объекта HighScore?

ответ

0

Просто измените getHighScore как следующий

public int getHighScore(Integer Level){ 

    // 1. get reference to readable DB 
    SQLiteDatabase db = this.getReadableDatabase(); 

    // 2. build query 
    Cursor cursor = 
      db.query(TABLE_HIGHSCORES, // a. table 
        COLUMNS, // b. column names 
        " Level = ?", // c. selections 
        new String[] { String.valueOf(Level) }, // d. selections args 
        null, // e. group by 
        null, // f. having 
        null, // g. order by 
        null); // h. limit 

    // 3. if we got results get the first one 
    if (cursor != null) 
     cursor.moveToFirst(); 

    // 4. return highScore 
    return cursor.getInt(2); 

} 

Вместо создания HighScore объекта, просто возвращает значение HighScoreInteger.

+0

Спасибо Патрику. Это работает! К сожалению, хотя я должен подождать 7 минут, чтобы отметить этот пост в качестве ответа. Еще раз спасибо. –

Смежные вопросы