Niks Niks - 3 years ago 155
Java Question

App crashes every time a SharedPreference gets requested

I want to store a int for 2 activities, in the first it gets loaded and in in the other one stored (and loaded to compare if its still the same).

Activity A:

textView = (TextView) findViewById(;

SharedPreferences preferences = getSharedPreferences("Pref", 0);
int score = preferences.getInt("Highscore", 0);

Activity B (in the onPause() part):

SharedPreferences preferences = getSharedPreferences("Pref", 0);
int pref_score = preferences.getInt("Highscore", 0);

if (new_score > pref_score) {
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("Highscore", gameView.getScore());

When I run the app it crashes immediately. Activity A gets called at first, it may be a problem that there is nothing stored so far?
If I comment it out in Activity A it works until the onPause() function in B gets called (Home Button).

Changed all to int, still crashing logcat

Answer Source

In Activity A you use preferences.getInt() while in Activity B you use preferences.edit().putString().

After you've fixed this, you will have to uninstall/reinstall your app or override the String value contained in your SharedPreference or it will still crash when you try to get it through getInt().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download