Weird exception: Cannot cast String to Boolean when using getBoolean

后端 未结 7 1833
温柔的废话
温柔的废话 2021-01-04 04:44

I\'m getting a very weird error. I have 2 activities. On both I\'m getting the SharedPreferences using MODE_PRIVATE (if it matters) by sp = g

相关标签:
7条回答
  • 2021-01-04 05:31

    I am assuming that

    sp.getBoolean(IntroActivity.SHOW_INTRO, true)// this line returns a String value.
    

    so you can do like this

    boolean showIntro = Boolean.parseBoolean(sp.getBoolean(IntroActivity.SHOW_INTRO, true));
    
    0 讨论(0)
  • 2021-01-04 05:31

    Got this exception when, by mistake, I've given to two preferences the same key in the XML file android:key="your_key"!

    So double checking your settings.xml may help.

    0 讨论(0)
  • 2021-01-04 05:34

    The exception occurs in this Android method:

    public boolean getBoolean(String key, boolean defValue) {
        synchronized (this) {
            awaitLoadedLocked();
            Boolean v = (Boolean)mMap.get(key); // On this line
            return v != null ? v : defValue;
        }
    }
    

    The only sense I can make of this error is that your are reusing the key IntroActivity.SHOW_INTRO for a String somewhere else in your code.

    0 讨论(0)
  • 2021-01-04 05:35

    The line sp.getBoolean(IntroActivity.SHOW_INTRO, true)// this line returns a String value.

    so you have to do as given below,

    String flag=sp.getBoolean(IntroActivity.SHOW_INTRO, true);
    
    if(flag.equalsIgnoreCase("true")){
        boolean showIntro = true;   
    }else{
        boolean showIntro = false;
    }
    

    Try this it will definitely works.

    0 讨论(0)
  • 2021-01-04 05:40

    If there's ever been a string with that key, even if by accident, it will stay there until you clear the app's data or uninstall. Try uninstalling it to see if it still occurs.

    0 讨论(0)
  • 2021-01-04 05:41

    Use the below code to set the boolean value in SharedPreference:

        SharedPreferences appSharedPrefs = PreferenceManager
                .getDefaultSharedPreferences(this.getApplicationContext());
        Editor prefsEditor = appSharedPrefs.edit();
        prefsEditor.putBoolean(IntroActivity.SHOW_INTRO, true);
        prefsEditor.commit();
    

    And to retrieve the boolean value from SharedPreference use this code:

    SharedPreferences appSharedPrefs = PreferenceManager
                .getDefaultSharedPreferences(this.getApplicationContext());
        boolean showIntro = appSharedPrefs.getBoolean(IntroActivity.SHOW_INTRO, true);
    
    0 讨论(0)
提交回复
热议问题