NullPointerException when trying to insert into SQLite - Android

前端 未结 2 1282
小鲜肉
小鲜肉 2021-01-25 11:13

Anyone who follows Android tags are probably familiar with me. I am having the hardest time implementing a SQLite database for my highscores. This is also my first time workin

相关标签:
2条回答
  • 2021-01-25 11:38

    Instead of

    dh.openDB(db);
    

    say

    db = dh.openDB(db);
    

    (although the openDB method really doesn't need to have an argument). Your call to openDB doesn't store the database object reference in db, so it's NULL when you get around to calling dh.insert(..., db);.

    0 讨论(0)
  • 2021-01-25 11:46

    On this line, you open the DB:

    dh.openDB(db);
    

    This stores the member variable of the database in DatabaseHelper.db (but nowhere else, and particularly not in Highscores.db). Then, you call:

    dh.insert(x, y, db);
    

    Using a null db object from Highscores. Lastly, within insert(), you use this null db object:

    return db.insert(TABLE, null, values);
    

    What you should do instead is use the following as your insert() method:

    public long insert(long score, int percentage) { // Remove db parameter
        ContentValues values = new ContentValues();
        values.put(SCORE, score);
        values.put(PERCENTAGE, percentage);
    
        return db.insert(TABLE, null, values); // This will use the member variable
    }
    

    Then, call dh.insert(x, y); instead.

    You should also change openDB(SQLiteDatabase db) to openDB() so that it is writing the correct DB; as it stands, it just overwrites the local variable's value (which changes nothing once the function's scope is done).

    0 讨论(0)
提交回复
热议问题