2014-02-27 25 views
-2

我想爲我的Android遊戲創造了很高的分數功能試圖做對證的SQLite數據庫

我想對證的SQLite數據庫,使用光標要經過查詢,以匹配一個串。如果名稱中有匹配,我希望它只是在更高的分數時更新分數。

如果名稱中沒有匹配,那麼我希望它輸入名稱和得分作爲新的高分。

然而,放入斷點後,無論已經存在的名稱都添加新的分數。所以我的檢查,看看名稱是否存在是行不通的。

這是從我的課堂,我執行所有數據庫功能的代碼片斷,

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

'查詢,以匹配一個string' - 所以,你應該添加一個WHERE ** **子句,匹配一個名字,你不? –

+0

試試cursor.getString(cursor.getColumnIndex(「whichPlayer」)),然後比較這個值在條件內。 –

+0

對於你的問題,例如你在數據庫中究竟有什麼(字段名稱),並且有一個例子試圖解釋你到底想要達到什麼目的,你能更具體一些嗎?所有的java文件你在用什麼? – user3213851

回答

1

你爲什麼想用cursor.moveToNext比較()?該函數只返回true或false,並用於移動到下一行。

從遊標的使用得到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 
} 
+0

我已經嘗試過這樣,我得到了一個致命的異常,我會把它放在我的問題 – dhali

+0

添加日誌這個答案上面 – dhali

+0

已更新的答案。你的數據庫結構又是什麼? – muktupavels