Search code examples
javaandroidsharedpreferencesandroid-sharedpreferences

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(R.id.score);

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

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());
    editor.commit();
}

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).

Edit Changed all to int, still crashing logcat


Solution

  • You're using "putString", and "getInt".
    So you save it as a String, but try and get it as an Integer. So it tries to cast the String to an Int, thus the ClassCastException.

    You have to save and get it as the same type.