Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PreferenceActivity with multiple preference files

The way to use a preference file (instead of the default shared preferences) in PreferenceActivity is as follows:

public class MyPreferencesActivity extends PreferenceActivity {
    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);

         PreferenceManager prefMgr = getPreferenceManager();
         prefMgr.setSharedPreferencesName("my_preferences");
         prefMgr.setSharedPreferencesMode(MODE_WORLD_READABLE);

         addPreferencesFromResource(R.xml.preferences);
    }
}

In this example we use the Shared Preference named "my_preferences". But how would we use more than one custom preference in the same PreferenceActivity?

like image 597
mae Avatar asked Aug 08 '12 18:08

mae


1 Answers

Declare the names of your preference files and while retriving the preferences, mention the name of that file which you want to access in getSharedPreferences().

Here I declare two file names : PrefFile and PrefFileNEW; then I pass the respective names to the getSharedPreference() while retrieving the preferences.

    public static final String PREF_FILE_NAME = "PrefFile";
    public static final String PREF_FILE_NAME_NEW = "PrefFileNEW";
    SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
{
//access your preferences here
}

SharedPreferences preferences_new = getSharedPreferences(PREF_FILE_NAME_NEW, MODE_PRIVATE);

{
//access your preferences_new here
}

Hope it helps.

like image 157
Swayam Avatar answered Oct 13 '22 00:10

Swayam