Most of examples I've found show a way to set default value in xml. I need to set default value in the codebehind.
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);
                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);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With