Showing posts with label Preferences. Show all posts
Showing posts with label Preferences. Show all posts

Android - How to get SharedPreferences from PreferenceActivity


I am using a PreferenceActivity to show some settings for my application. I am inflating the settings via a xml file so that my onCreate (and complete class methods) looks like this:

public class FooActivity extends PreferenceActivity { 
 
 @Override 
 public void onCreate(Bundle icicle) { 
  super.onCreate(icicle); 
  addPreferencesFromResource(R.xml.preference); 
 } 
 
} 

The javadoc of PreferenceActivity states, that
These preferences will automatically save to SharedPreferences as the user interacts with them. To retrieve an instance of SharedPreferences that the preference hierarchy in this activity will use, call getDefaultSharedPreferences(android.content.Context) with a context in the same package as this activity.
But how I get the name of the SharedPreference in another Activity? I can only call
getSharedPreferences(name, mode) in the other activity but I need the name of the SharedPreference which was used by the PreferenceActivity. What is the name or how can i retrieve it?


Android - Display current value of Preference in Preference summary


When the user is editing preferences in an Android app, I'd like them to be able to see the currently set value of the preference in the Preference summary.

Example: if I have a Preference setting for "Discard old messages" that specifies the number of days after which messages need to be cleaned up. In the PreferenceActivity I'd like the user to see:

"Discard old messages" <- title

"Clean up messages after x days" <- summary where x is the current Preference value

Extra credit: make this reusable, so I can easily apply it to all my preferences regardless of their type (so that it work with EditTextPreference, ListPreference etc. with minimal amount of coding).

Popular Posts