Lidia
Lidia

Reputation: 445

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

Upvotes: 9

Views: 15955

Answers (3)

kamasuPaul
kamasuPaul

Reputation: 323

You can use the XML attribute android:defaultValue="true" on your <SwitchPreference /> to set the default to true.

Upvotes: 3

Lidia
Lidia

Reputation: 445

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();

Upvotes: 7

Carl-Emil Kjellstrand
Carl-Emil Kjellstrand

Reputation: 1243

If you trying to get the boolean out of newValue

        boolean selected =   Boolean.parseBoolean(newValue.toString());      

your going about this in a strange and I guess incorrect way. If newValue is a Boolean, (check with instanceof) then just cast newValue to be a Boolean.

        boolean selected =   (Boolean) newValue;

Is that what your trying to achieve?

Upvotes: 1

Related Questions