0

I'm retrieving an integer value from the sharedpreferences like this:

AudioManager Am = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
    int errorThisLine250 = prefs.getInt("adanvlm", Am.getStreamMaxVolume(AudioManager.STREAM_MUSIC));

and I'm getting this error !!!

java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
        at android.app.SharedPreferencesImpl.getInt(SharedPreferencesImpl.java:239)
        at aim.salatuna7.dialogs.AdanDialog.onCreateDialog(AdanDialog.java:250)

The starnge here is that the app was works great without any errors, today it starts showing this error whenever I show the dialog. The error is at the int errorThisLine250. Any suggestions?

Edit: I tried:

Integer.parseInt(prefs.getString("adanvlm", String.valueOf(Am.getStreamMaxVolume(AudioManager.STREAM_MUSIC))));

and it is NOT working too.

Leebeedev
  • 2,126
  • 22
  • 31

2 Answers2

1

Apparently, tou originally had this SharedPreference as a string preference, then changed it to be an integer preference.

Uninstall and reinstall your app, thereby deleting the contents of internal storage and getting rid of the old edition of your preferences.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • or add 'backward compatibility' code that does the prefs.getInt() in a try-catch block, and then try to getString if ClassCastException is thrown! – RobP Dec 24 '14 at 21:55
  • Thank you for the very fast reply, but I tried all what you have said many times with no luck! any help please? I'm stuck @commonsWare – Leebeedev Dec 24 '14 at 21:56
  • @CommonsWare, I'm using the preference.xml like so – Leebeedev Dec 24 '14 at 21:58
  • @Aimen7: An `EditTextPreference` saves a string, not an int. You need to use `getString()` to retrieve the preference, then worry about parsing it to be an `Integer` if you so choose. – CommonsWare Dec 24 '14 at 22:31
  • @CommonsWare I tried like so: Integer.parseInt(prefs.getString("bfrvlm", String.valueOf(Am.getStreamMaxVolume(AudioManager.STREAM_MUSIC)))); – Leebeedev Dec 24 '14 at 22:33
0

Looks like your EditTextPreference has a default value that is string:

<EditTextPreference android:defaultValue="0" android:key="adanvlm" />

So, it is probable but a bit odd, that you many continue along using the string version and convert that string to an int before using it in your dialog and elsewhere where an int is needed.

// get the preference value as a string
String adanvlmString = prefs.getString("adanvlm", String.valueOf(Am.getStreamMaxVolume(AudioManager.STREAM_MUSIC)));
// convert the preference value from string to int
int adanvlmInt = Integer.parseInt(adanvlmString);

Or you could subclass EditTextPreference as follows here : PreferenceActivity: save value as integer

Community
  • 1
  • 1
petey
  • 16,914
  • 6
  • 65
  • 97