Search code examples
javaandroidsharedpreferences

Using Shared Preferences to save a high score in an Android game


I have made an android game and wish to save highscores using Shared preferences. I have created a class which extends Application but receive a null pointer exception on:

SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);

I would appreciate some example code on how to save and load shared preferences as other examples are causing this null pointer exception.

06-12 17:53:55.864: E/AndroidRuntime(13923): FATAL EXCEPTION: Thread-17335
06-12 17:53:55.864: E/AndroidRuntime(13923): java.lang.NullPointerException
06-12 17:53:55.864: E/AndroidRuntime(13923):    at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:173)
06-12 17:53:55.864: E/AndroidRuntime(13923):    at MyApplication.save(MyApplication.java:22)
06-12 17:53:55.864: E/AndroidRuntime(13923):    at GameScreen.drawGameOverUI(GameScreen.java:609)
06-12 17:53:55.864: E/AndroidRuntime(13923):    at GameScreen.paint(GameScreen.java:493)
06-12 17:53:55.864: E/AndroidRuntime(13923):    at framework.implementation.AndroidFastRenderView.run(AndroidFastRenderView.java:48)
06-12 17:53:55.864: E/AndroidRuntime(13923):    at java.lang.Thread.run(Thread.java:841)

Solution

  • It can be easily done in a couple of lines:

    SharedPreferences preferences = getSharedPreferences(APP_NAME, MODE_PRIVATE);
    preferences.edit().putInt(SELECTED_POSITION, position).commit();
    

    Where APP_NAME is a String, SELECTED_POSITION is another String and position an int, which I want to store.

    And to get it:

    SharedPreferences preferences = getSharedPreferences(APP_NAME, MODE_PRIVATE);
    preferences.getInt(SELECTED_POSITION, 0);