Question

I have multiple views that come and go as the application runs. I want each view to have its own personal preferences that are stored as the ID tag of the view. Above these is the "General Preferences" that the sub prefs reference to get their default values when a view it is created.

Right now I have it set up that the General Preferences are the default SharedPreferences. But I have no Idea how to create the new preferences and set up an activity UI so the user can change them. Is it pretty much the same as setting up the SharedPreferences?

Was it helpful?

Solution

this may not be exactly what you're asking for, but here's what I do:

in my main activity, when I call the preferences activity, I pass it the name of the custom preference file as extra data in the intent:

static final String EXTRA_PREFERENCES_NAME = "android.intent.extra.PREFERENCES_NAME";
...
Intent intent = new Intent(this, Preferences.class);
intent.putExtra(EXTRA_PREFERENCES_NAME, preferencesName);
startActivity(intent);

then, in my preferences activity, I get the custom preferences name and set it like this:

public class Preferences extends PreferenceActivity {
    private String preferencesName = "";

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

    // get the custom preferences name from the extra data in the intent
    preferencesName = getIntent().getExtras().getString(MainActivity.EXTRA_PREFERENCES_NAME);
    // set the preferences file name
    getPreferenceManager().setSharedPreferencesName(preferencesName);
    // get the default preferences from XML
    addPreferencesFromResource(R.xml.preferences);
}

lastly, in my main activity, I get specific preferences like this:

SharedPreferences preferences = getSharedPreferences(preferencesName, MODE_PRIVATE);
String somePreference = preferences.getString("somePreference", defaultValue);

OTHER TIPS

Somehow I am not worthy to comment but to write an answer, so here we go: I'd really like to know how to use sharedPreferences with PreferencesActivity instead of DefaultSharedPreferences.

One way I can think of to accomplish this is letting the preferenceActivity save the values to defaultSharedPreferences and then read these values out and save them into a sharedPreferences associated with a name that would match the kind of values saved.

But this seems very wrong. So how do you guys do this? Or do you save all your values from any PreferencesActivties into defaultSharedPreferences?

You can use PreferenceManager to achieve the objective.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top