Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change state of a preference item from outside the PreferenceActivity?

There are some features in my app which require android version 4.2+. So in my main activity, i will need to check for available OS features and modify(Enable/Disable)preferences items which are defined in my PreferenceActivity.

The following code is unreachable from outside the PreferenceActivity

ListPreference prefReport = (ListPreference)getPreferenceScreen().findPreference("pref_report");
prefDspProfile.setValue("0");

So my question is how to modify preferences items from outside PreferenceActivity.

like image 967
Mehdi Fanai Avatar asked Mar 06 '13 15:03

Mehdi Fanai


1 Answers

If you use a PreferenceAcitivity implicitly you are using a SharedPreference file. So, outside your PreferenceAcitivity you can access your SharedPrefence file and change it. Soon, those changes will be reflected on your PreferenceActivity.

You need a Context to access a SharedPreference. Look forward for example on onCreate method of other simpleAcitivity.

UPDATE: Using this approach you are not able to enable/disable items. You can change their values or remove them

@Override
protected void onCreate(Bundle state){
   super.onCreate(state);

   // Restore preferences
   SharedPreferences settings = getPreferences(MODE);
   // Make sure we're running on Honeycomb or higher to use ActionBar APIs
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
      //change your setting here
      // We need an Editor object to make preference changes.
      // All objects are from android.context.Context
      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putBoolean("silentMode", mSilentMode);

      // Commit the edits!
      editor.commit();
   }

}

Other way, and on my opinion better and easier is Provide Alternative Resource. You can provide many xml files, that defines your app settings, according the Android API level, using a resource qualifier. For instance: v2, v17.

 res-v4
     setting.xml

 res-v17
     setting.xml -> This file can include specific Jelly Beans configs  
like image 193
Bruno Mateus Avatar answered Nov 15 '22 00:11

Bruno Mateus