user2005938
user2005938

Reputation: 179

Error saving using SharedPreferences

I am saving a few variables using sharedpreferences but my save method crashes the app with a null pointer exception.

public void save() {

    SharedPreferences sp = context.getSharedPreferences(saveFile, Context.MODE_PRIVATE);
    //Use the editor for easier management, no calling edit and commit so many times. 
    SharedPreferences.Editor editor = sp.edit();

    editor.putInt("X", player.getX());
    editor.putInt("Y", player.getY());
    editor.putInt("level", player.getLevel());
    editor.putFloat("xp", player.getXp());
    editor.commit();
}

getSharedPreferences() does not work by itself and needs to have context. before it, which could be a problem. I have context defined, SharedPreferences imported, so why does this not work?

EDIT: Here is the logcat

02-18 20:21:49.958: E/AndroidRuntime(1005): FATAL EXCEPTION: Thread-89
02-18 20:21:49.958: E/AndroidRuntime(1005): java.lang.NullPointerException
02-18 20:21:49.958: E/AndroidRuntime(1005): at com.package.game.GameScreen.save(GameScreen.java:856)
02-18 20:21:49.958: E/AndroidRuntime(1005): at com.package.game.GameScreen.updateLevelUp(GameScreen.java:364)

The save method is above and the line:

SharedPreferences sp = context.getSharedPreferences(saveFile, Context.MODE_PRIVATE);

is line 856. updateLevelUp is the method that is called when the player levels up and when that screen is exited the game resumes and save() is called.

Upvotes: 0

Views: 674

Answers (2)

Raghav Sood
Raghav Sood

Reputation: 82553

Your context variable is null. Make sure that it has been initialized, and that you aren't calling this code before the onCreate() of the respective Context.

Upvotes: 1

daniel_c05
daniel_c05

Reputation: 11518

As a good rule, you want to utilize a SharedPreferences.Editor when managing SharedPreferences.

Here's a simpler way:

public void save() {
    SharedPreferences saveFile = context.getSharedPreferences(loadSave, Context.MODE_PRIVATE);
    //Use the editor for easier management, no calling edit and commit so many times. 
    SharedPreferences.Editor editor = saveFile.edit();

    editor.putInt("x", player.get());
    editor.putInt("Y", player.getY());
    editor.putInt("level", player.getLevel());
    editor.putFloat("xp", player.getXp());

    //Save changes now
    editor.commit();
}

Also, in case you still get a nullpointer after this implementation, make sure you post the log so we can track down the exception.

Upvotes: 0

Related Questions