Here is my code for game i use to save high score
SharedPreferences preferences = null;
SharedPreferences.Editor editor = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
//Highscore.easyHigh = 0;
Highscore.easyHigh = preferences.getInt("EasyScore", 0);
Highscore.mediumHigh = preferences.getInt("MediumScore", 0);
Highscore.hardHigh = preferences.getInt("HardScore", 0);
Now i set these values when player looses the game
editor = preferences.edit();
if(level==1)
editor.putInt("EasyScore", score);
else if(level==2)
editor.putInt("MediumScore", score);
else if(level==3)
editor.putInt("HardScore", score);
editor.commit();
Highscore is my class storing public static int easy, medium , hard?
I get a null pointer exception but why does that happen?
Your preferences and editor values are not initalized, use this :
preferences = PreferencesManager.getDefaultSharedPreferenes(this);
editor = preferences.edit();
You havent initialised preferences
and editor
..Do it after setContentView()
in your code..
Do it like this..
preferences = PreferencesManager.getDefaultSharedPreferenes(this);
editor = preferences.edit();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.