【问题标题】:SQLite or SharedPreferences for High Scores高分的 SQLite 或 SharedPreferences
【发布时间】:2014-06-23 03:38:27
【问题描述】:

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

这是我的 onFinish 代码:

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();

【问题讨论】:

  • 您是否使用 sqlite 在您的应用中获得前 10 名?
  • 你开始为 sqlite db 编写代码了吗?如果没有,这里有一个很好的教程androidhive.info/2011/11/android-sqlite-database-tutorial
  • SQLite 仅存储 10 位数字似乎不可行...在我看来,您应该坚持使用 SharedPreferences

标签: android sqlite sharedpreferences


【解决方案1】:

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

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

DatabaseHandler db = new DatabaseHandler(this);

然后为数据库使用增加价值,db.addScore(count);

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

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;
}

}

【讨论】:

    【解决方案2】:

    如果您只是要保存和显示特定数量的记录,您可以使用共享首选项本身,如下所示:

    public class Highscore {
    private SharedPreferences preferences;
    private String names[];
    private long score[];
    
    public Highscore(Context context)
    {
    preferences = context.getSharedPreferences("Highscore", 0);
    names = new String[10];
    score = new long[10];
    
    for (int x=0; x<10; x++)
    {
    names[x] = preferences.getString("name"+x, "-");
    score[x] = preferences.getLong("score"+x, 0);
    }
    
    }
    
    public String getName(int x)
    {
    //get the name of the x-th position in the Highscore-List
    return names[x];
    }
    
    public long getScore(int x)
    {
    //get the score of the x-th position in the Highscore-List
    return score[x];
    }
    
    public boolean inHighscore(long score)
    {
    //test, if the score is in the Highscore-List
    int position;
    for (position=0; position<10&&this.score[position]>score; 
    position+
    +);
    
    if (position==10) return false;
    return true;
    }
    
    public boolean addScore(String name, long score)
    {
    //add the score with the name to the Highscore-List
    int position;
    for (position=0; position<10&&this.score[position]>score; 
    position+
    +);
    
    if (position==10) return false;
    
    for (int x=9; x>position; x--)
    {
    names[x]=names[x-1];
    this.score[x]=this.score[x-1];
    }
    
    this.names[position] = new String(name);
    this.score[position] = score;
    
    SharedPreferences.Editor editor = preferences.edit();
    for (int x=0; x<10; x++)
    {
    editor.putString("name"+x, this.names[x]);
    editor.putLong("score"+x, this.score[x]);
    }
    editor.commit();
    return true;
    
    }
    
    }
    

    参考:http://osdir.com/ml/Android-Developers/2010-01/msg00794.html

    但是,最好使用 SQLite,因为可以在获取自身的同时对分数进行排序。你可以使用一个简单的算法,

    • SELECT 'TRUE' WHERE CURRENT_SCORE &gt; MIN(EXISTING_HIGH_SCORES);
    • 如果记录可用,并且现有高分数 > 10,则 DELETE RECORD FROM MY_TABLE WHERE SCORE = MIN(EXISTING_HIGH_SCORES)
    • 将当前分数插入数据库。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多