我是一个 sqlite 新手。我正在尝试做什么...我有一个游戏,游戏结束后它将时间结果存储在一个名为 elapsedSeconds 的双变量中。我想将该结果放在一个数据库中,然后在我的专用活动中显示用户的前 10 名。我有创建数据库的 HighScoreDb 类(我使用了一些我在网上找到的代码,但我认为它会达到我的目的)。这是代码。
public class HighScoreDb {
private static class HighScoreDbHelper extends SQLiteOpenHelper {
public HighScoreDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(SCORE_TABLE_CREATE);
} catch (SQLException e) {
Log.i("Error", "Error making database");
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + SCORE_TABLE_NAME);
onCreate(db);
}
}
private static final int DATABASE_VERSION = 2;
private static final String SCORE_TABLE_NAME = "highscore";
private static final String SCORE_TABLE_CREATE = "CREATE TABLE "
+ SCORE_TABLE_NAME
+ " (_id INTEGER PRIMARY KEY autoincrement, "
+ "name TEXT NOT NULL, score DOUBLE NOT NULL)";
private static final String DATABASE_NAME = "highscores.db";
// The index (key) column name for use in where clauses.
public static final String KEY_ID = "_id";
// The name and column index of each column in your database.
public static final String KEY_NAME = "name";
public static final String KEY_SCORE = "score";
public static final int NAME_COLUMN = 1;
public static final int NUMBER_COLUMN = 2;
public static final int SCORE_COLUMN = 3;
SQLiteDatabase db;
private final Context ctx;
private final HighScoreDbHelper dbHelper;
public HighScoreDb(Context context) {
this.ctx = context;
ctx.deleteDatabase(SCORE_TABLE_NAME);
dbHelper = new HighScoreDbHelper(context);
db = dbHelper.getWritableDatabase();
}
public void close() {
if (db != null) {
db.close();
}
}
public void createRow(String name, int score) {
ContentValues intialValue = new ContentValues();
intialValue.put("name", name);
intialValue.put("score", score);
db.insertOrThrow(SCORE_TABLE_NAME, null, intialValue);
}
public void deleteRow(long rowId) {
db.delete(SCORE_TABLE_NAME, "_id=" + rowId, null);
}
public Cursor GetAllRows() {
try {
return db.query(SCORE_TABLE_NAME, new String[] { "_id", "name", "score" }, null,
null, null, null, "score DESC");
} catch (SQLException e) {
Log.i("Error on query", e.toString());
return null;
}
}
public void updateRow(long _id, String name, String score) {
ContentValues args = new ContentValues();
args.put("name", name);
args.put("number", score);
db.update(SCORE_TABLE_NAME, args, "_id=" + _id, null);
}
}
从这个表中我不需要列名,因为我只有 10 个有分数的地方。我的游戏结束后如何将该结果插入到这个数据库中?我想我知道如何从中阅读,我会做这样的事情:
HighScoreDb db = new HighScoreDb(this);
Cursor myCursor = db.GetAllRows();
myCursor.moveToPosition(0);
String Row1Value2 = myCursor.getString(2);
myCursor.close();
db.close();
我在我的游戏课上这样称呼它:
HighScoreDb db = new HighScoreDb(this);