我正在学习如何使用 sqlite 数据库,并且我尝试在我制作的游戏中实现高分系统。当我尝试显示分数时读取行有效,但是当我尝试使用相同的想法读取值以在以下方法中比较它们时 - 它给出空指针异常错误。
private void checkIfHighScore(int currentScore) {
Cursor note;
int rowScore;
String moveName, moveScore, newName;
for (long i=1;i<6;i++){
note = mDbHelper.fetchNote(i);
startManagingCursor(note);
rowScore=Integer.parseInt(note.getString(note.getColumnIndexOrThrow(ScoresDbAdapter.KEY_BODY)));
if (currentScore<rowScore){
for (long j=5;j>i;j--){
note = mDbHelper.fetchNote(j-1);
startManagingCursor(note);
moveName=note.getString(note.getColumnIndexOrThrow(ScoresDbAdapter.KEY_TITLE));
moveScore=note.getString(note.getColumnIndexOrThrow(ScoresDbAdapter.KEY_BODY));
mDbHelper.updateNote(j, moveName, moveScore);
}
newName="a"; //for testing
mDbHelper.updateNote(i, newName, Integer.toString(currentScore));
break;
}
}
}
我知道错误在 for 循环之后的那一行 - 但我不知道是什么导致它失败。我的数据库有 5 行数据(已验证)。 有谁知道是什么导致了我的错误?为此,我用头撞墙 2 小时。谢谢!
最佳答案
除了您拥有的代码,您还可以执行类似
的操作String selectQuery = "SELECT MAX(COLUMN_NAME) FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor.moveToFirst(){
rowScore = Integer.parseInt(cursor.getString(0);
if(rowScore < currentScore){
//you have a new high score
}
}
通过这种方式,您可以利用 SQLite 附带的预定义函数,这些函数速度更快,并且可以节省一些工作。
关于java - 奇怪的 nullPointerException 错误 - 数据库相关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9850520/