Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default value for preferences in PreferenceFragment dynamically (not via xml)

Most of examples I've found show a way to set default value in xml. I need to set default value in the codebehind.

  1. Is calling setDefaultValue(..) like in the code below a proper way to do it?
  2. How to have this value to be displayed when user tries to change this preference. I have empty EditText displayed.

Note: the value of

Environment.getExternalStorageDirectory().getPath() + "/BasicCommunicationWithAndroid.log"

is /storage/sdcard0/BasicCommunicationWithAndroid.log so it's not null nor empty string

    public class SettingsFragment extends PreferenceFragment
    {
        private Preference _pref_log_logFilenameOnSDCard;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);

            loadPreferences();
        }

        private void loadPreferences()
        {
            _pref_log_logFilenameOnSDCard = (Preference) findPreference("pref_log_logFilenameOnSDCard");
            _pref_log_logFilenameOnSDCard.setDefaultValue(Environment.getExternalStorageDirectory().getPath() + "/BasicCommunicationWithAndroid.log");    
        }
    }

And in MainActivity in onCreate(..) I have:

PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
like image 487
lixonn Avatar asked Mar 08 '14 21:03

lixonn


1 Answers

I had the same problem and solved it like this:

public class SettingsFragment extends PreferenceFragment {

 @Override
 public void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);

  // Load the preferences from an XML resource
  addPreferencesFromResource(R.layout.settings_fragment);


  ListPreference listPreference = (ListPreference) findPreference("user");
  if(listPreference.getValue()==null) {
      // to ensure we don't get a null value
      // set first value by default
      String defaultValue = "Smith";
      PreferenceManager.getDefaultSharedPreferences(getActivity()).getString("user", defaultValue);
      listPreference.setValue(defaultValue);
  }
  // this part just shows how I set a summary field on the element onChange and initially
  listPreference.setSummary(listPreference.getValue().toString());
  listPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
      @Override
      public boolean onPreferenceChange(Preference preference, Object newValue) {
          preference.setSummary(newValue.toString());
          return true;
      }
  });
 }
}

So just use this part:

PreferenceManager.getDefaultSharedPreferences(getActivity()).getString("user", defaultValue);
like image 150
Martin Avatar answered Oct 06 '22 12:10

Martin