NullPointerException when trying to insert into SQLite - Android

前端 未结 2 1314
小鲜肉
小鲜肉 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: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).

提交回复
热议问题