我正在尝试为我的安卓游戏创建高分功能
我正在尝试检查sqlite db,使用游标通过查询将其与字符串进行匹配。如果名称中有匹配项,我希望它只是更新得分。
如果名称中没有匹配项,那么我希望它输入名称并将分数作为新的高分。
然而,在输入断点后,无论名称是什么,它都会添加新分数。所以我检查名称是否存在无效。
这是我班级中执行所有数据库功能的代码片段,
SQLiteDatabase database = this.getWritableDatabase();
// I store the name string in the game as a ContentValue called queryValues to use here
// I use a cursor to go through query
ContentValues values = new ContentValues();
String selectQuery = "SELECT whichPlayer FROM highScore";
Cursor cursor = database.rawQuery(selectQuery, null);
if ((queryValues.get("whichPlayer").equals(cursor.moveToNext()))) {
// The code here is to update score, as the check above should denote that a name already exists
// However it goes straight to the else (To enter a new player)
我不知道我在哪里出错,因为没有显示任何错误,因此我的逻辑存在问题。我对编程很新,所以这可能是一个愚蠢的错误
问题清晰需要更多代码吗?
任何帮助将不胜感激。
尝试albertsmuktupavels回答后我得到了
E/AndroidRuntime(26483): FATAL EXCEPTION: main
E/AndroidRuntime(26483): Process: com.example.con4, PID: 26483
E/AndroidRuntime(26483): android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0
E/AndroidRuntime(26483): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)
E/AndroidRuntime(26483): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
E/AndroidRuntime(26483): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
加上一点指向
String checkPlayer = cursor.getString(cursor.getColumnIndex("whichPlayer"));
答案 0 :(得分:1)
为什么要尝试与cursor.moveToNext()进行比较?该函数只返回true或false,用于移动到下一行。
要从光标获取whichPlayer值,请使用:
String whichPlayer = cursor.getString(cursor.getColumnIndex("whichPlayer"));
比你可以尝试这样比较:
cursor.moveToFirst();
do {
if (queryValues.get("whichPlayer").equals(whichPlayer)) {
// ...
}
} while (cursor.moveToFirst());
编辑: 我假设你有一个至少有两个字段的表,每个玩家只有一行得分。 字段:得分(整数),whichPlayer(文本)
SQLiteDatabase database = this.getWritableDatabase();
String whichPlayer = "somePlayer";
int newScore = 4500;
// Select current player's previous score
Cursor cursor = database.rawQuery("SELECT score FROM highScore WHERE whichPlayer = ?", new String[] { whichPlayer });
if (cursor != null && cursor.getCount() != 0) {
// We have score in database for this player
cursor.moveToFirst();
// Get score for this player
int score = cursor.getInt(cursor.getColumnIndex("score"));
// Check if your new score is higher
if (newScore > score) {
// update your score with new one
}
} else {
// There is no score stored for this player - insert if you want
}