Search code examples
javaandroidandroid-preferences

How to set default value for SwitchPreference in Android?


Does anyone used SwitchPreference class from Android and knows how to set the default value? I have implemented it programmatically:

SwitchPreference switch = new SwitchPreference(this);
switch.setKey("preference_my_key");
switch.setTitle(R.string.preference_title_my_title);
switch.setSummary(R.string.preference_summary_my_summary);
Boolean isChecked = Manager.myMethodIsChecked(MyActivity.this);
switch.setChecked( isChecked ); 

switch.setOnPreferenceChangeListener(new OnPreferenceChangeListener()  {                
    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
    try {
            boolean selected =   Boolean.parseBoolean(newValue.toString());      
        if ( !selected ) {
            //do something
        }
    } catch (Throwable e) {
       e.printStackTrace();
    }               
   return true;
   }
});         
category.addPreference(switch);

Preferences saves all values into its XML file: app_package_name_preferences.xml. First time when app is loaded, switch has default "false " values. But I need sometimes to make default value "true". I tried few methods,but nothing works.

switch.setChecked( true );  
switch.setDefaultValue(true);

Solution

  • As I told, I write preferences programmatically:

    PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);
    PreferenceCategory catView = new PreferenceCategory(this);
    catView.setTitle(R.string.preference_category_view);
    root.addPreference(catView);
    
    final SwitchPreference switchSplash= new SwitchPreference(this);
    switchSplash.setKey(PreferenceKeys.SPLASH); 
    
    //-----the above code----
    switchSplash.setChecked(false);       // LINE 1
    catView.addPreference(switchSplash);  // LINE 2
    

    While debugging I found that true value is set in LINE 1, but when I add switchSplash into catView, the values of switchSplash is reset to false, because catView sets values from preferences.xml.
    That's why I changed all needed values into the XML

    SharedPreferences.Editor editor = root.getPreferenceManager().getSharedPreferences().edit();
    editor.putBoolean(PreferenceKeys.SPLASH, true);  
    editor.commit();