高分的 SQLite 或 SharedPreferences [英] SQLite or SharedPreferences for High Scores

查看:59
本文介绍了高分的 SQLite 或 SharedPreferences的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的游戏中编写代码以在计时器超时后保存分数.我有我的分数,我有我的计时器.我已经阅读了一些关于 SharedPreferences 和 SQLite 的内容.我知道我想保存前 10 个高分,但 SharedPreferences 最好只保存 1 个分数.我正在尝试围绕 SQLite 进行思考,但我就是无法理解.任何人都可以帮助我找出一行代码来只保存前 10 个分数.

I am trying to write in a code in my game to save the score after the timer times out. I have my score and I have my timer. I've read a bit about SharedPreferences and SQLite. I know that I want to save the top 10 high scores, but SharedPreferences is best for just 1 score. I am trying to wrap my head around SQLite but I just cannot get it. Any chance someone could help me to figure out a line of code to save only the top 10 scores.

这是我的 onFinish 代码:

Heres my onFinish code:

public void onFinish() {
        textViewTimer.setText("00:000");
        timerProcessing[0] = false;

        /** This is the Interstitial Ad after the game */
        AppLovinInterstitialAd.show(GameActivity.this);

        /** This creates the alert dialog when timer runs out  */

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(GameActivity.this);
        alertDialogBuilder.setTitle("Game Over");
        alertDialogBuilder.setMessage("Score: " + count);
        alertDialogBuilder.setCancelable(false);
        alertDialogBuilder.setNeutralButton("Restart", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                Intent restartGame = new Intent(GameActivity.this, GameActivity.class);
                startActivity(restartGame);
                finish();
            }
        });

        alertDialogBuilder.setNegativeButton("Home", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id) {
                GameActivity.this.finish();             
            }

        });
        alertDialogBuilder.show();

推荐答案

您可以使用下面给出的代码来保存和检索任意数量的分数.创建一个名为 DatabaseHandler.java 的新数据库助手类,并在其中添加以下代码.

You can use the code given below to save any number of score and retrieve them. Create a new database helper class named, DatabaseHandler.java and add the following code in it.

要在您的活动中初始化类,请将以下行放入您的活动中:

To initialise the class in your activity, put the following line in your activity :

DatabaseHandler db = new DatabaseHandler(this);

然后给db使用添加值,db.addScore(count);

Then to add value to db use, db.addScore(count);

要从数据库中过滤掉前十个分数,您可以将 get 方法中的查询更改为:

To filter out just top ten scores from the db, u may change the query in get method to :

String selectQuery = "SELECT  * FROM " + TABLE_SCORE + "LIMIT 10";

.

public class DatabaseHandler extends SQLiteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "game";

// Table name
private static final String TABLE_SCORE = "score";

// Score Table Columns names
private static final String KEY_ID_SCORE = "_id";
private static final String KEY_SCORE = "score_value";

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

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_SCORE_TABLE = "CREATE TABLE " + TABLE_SCORE + "("
            + KEY_ID_SCORE + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + KEY_SCORE + " TEXT" + ")";

    db.execSQL(CREATE_SCORE_TABLE);

}

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

    // Create tables again
    onCreate(db);
}

// Adding new score
public void addScore(int score) {

    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();

    values.put(KEY_SCORE, score); // score value

    // Inserting Values
    db.insert(TABLE_SCORE, null, values);

    db.close();

}

// Getting All Scores
public String[] getAllScores() {

    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_SCORE;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list

    int i = 0;

    String[] data = new String[cursor.getCount()];

    while (cursor.moveToNext()) {

        data[i] = cursor.getString(1);

        i = i++;

    }
    cursor.close();
    db.close();
    // return score array
    return data;
}

}

这篇关于高分的 SQLite 或 SharedPreferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆