开发者

SQLite Android Problem

开发者 https://www.devze.com 2023-02-22 10:24 出处:网络
I am making a local high scores table using SQLite for my Android application (Java). For some reason, the application crashes while trying to add a new high score to the table. Here is the relevant

I am making a local high scores table using SQLite for my Android application (Java).

For some reason, the application crashes while trying to add a new high score to the table. Here is the relevant code:

private static String HIGHSCORES_TABLE_NAME = "SCORES_TABLE";
private SQLiteDatabase highScoresDB = null;
private Cursor cursor = null;

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);

    try
    {
        highScoresDB = openOrCreateDatabase("ScoresDatabase", MODE_PRIVATE, null);
        createTable();
        lookupData();
    }
    catch (SQLiteException se)
    {
        Log.e(getClass().getSimpleName(), "Could not create or Open the database");
    }
    finally
    {

        if (highScoresDB != null)
                           highScoresDB.execSQL("DELETE F开发者_运维百科ROM " + HIGHSCORES_TABLE_NAME);
        highScoresDB.close();
    }
}

private void createTable() {
    highScoresDB.execSQL("CREATE TABLE IF NOT EXISTS " + HIGHSCORES_TABLE_NAME + " (SCORE INT(3));");
}

private void insertData() {
    highScoresDB.execSQL("INSERT INTO " + HIGHSCORES_TABLE_NAME + " Values ("+ highscore +");");
}

private void lookupData() {
    cursor = highScoresDB.rawQuery("SELECT SCORE FROM " + HIGHSCORES_TABLE_NAME, null);
    if (cursor.moveToLast()) {
        highscore = cursor.getInt(cursor.getColumnIndex("SCORE"));
    }
    cursor.close();
}

public void restart() {
    insertData();
}

When I look up the high score, I only want the most recent one so I use moveToLast().


I found that "cursor.moveToLast()" does not seem to work correctly. It does move the position in the cursor, but throws an exception when you attempt to read that record.

This works:

cursor.moveToPosition(cursor.getCount()-1)


What is the exception that causes it to crash, When are you inserting a new row ? Are you opening the database before inserting a row , as Close() is being called on in the finally block of the create method.

If this is the only information you are going to store in the database , consider using Shared Preferences. This link has a demo of how to use it - Shared preferences demo


Instead of doing statements like you are doing use some of the provided methods that are included in the SQLite Object class:

http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html

This makes your code less error prone to SQL Typos or small errors.

Also please post your logcat.

0

精彩评论

暂无评论...
验证码 换一张
取 消