0

I'm reading SharedPreferences in my app at startup, and after a few runs it will crash and tell me that I'm trying to cast from a String to a Boolean. Below is the code that I use to read and write this value.

// Checks if the realm has been copied to the device, and copies it if it hasn't.
private void copyRealm() {
    final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    if (!sharedPreferences.getBoolean(getString(R.string.pref_copied), false)) {
        // Copy the realm to device.
        final String path = copyBundledRealmFile(getResources().openRawResource(R.raw.realm), getString(R.string.realm_name));

        // Save the path of the realm, and that the realm has been copied.
        sharedPreferences.edit()
                .putBoolean(getString(R.string.pref_copied), true)
                .putString(getString(R.string.pref_path), path)
                .apply();
    }
}

The two strange things are that it doesn't start happening for a few builds, and so far it has only happened on a simulator. I haven't been able to check a physical device yet, but I've also been running this code without change for several months and had no trouble.

Why would I be getting this message?

Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean at android.app.SharedPreferencesImpl.getBoolean(SharedPreferencesImpl.java:293)?

Paul Chu
  • 1,249
  • 3
  • 19
  • 27
Cody Harness
  • 1,116
  • 3
  • 18
  • 37

1 Answers1

-2

Take a look at this question Android getDefaultSharedPreferences.

It seems it's a better idea to just use

SharedPreferences preferences = getPreferences(MODE_PRIVATE);

or

SharedPreferences references1=getSharedPreferences("some_name",MODE_PRIVATE);

instead of using

SharedPreferences preferences= getDefaultSharedPreferences(this);

From the documentation:

getPreferences(MODE_PRIVATE) retrieves a SharedPreferences object for accessing preferences that are private to this activity. This simply calls the underlying getSharedPreferences(String, int) method by passing in this activity's class name as the preferences name.

I regularly use one of these two approaches and had no problem of any kind so far.

colens
  • 467
  • 3
  • 12