6

I want to show the value of preferences in a custom preference screen. For this I need to get the values, in this case strings, within the preference fragment. In non fragments (activities) I get the values with e.g. final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); and get the string with String phonenumber = prefs.getString("preference_name", null); but in the preference fragment getDefaultSharedPreferences is not applicable for preference fragment.

Any idea how to solve this?

Here's my code snippet:

public class PreferencesFragment extends PreferenceFragment implements
    OnSharedPreferenceChangeListener {

TextView tvusername, tvphonenumber;     

@Override
   public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     addPreferencesFromResource(R.xml.preferences);
     getPreferenceScreen().getSharedPreferences()
            .registerOnSharedPreferenceChangeListener(this);

     final SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(this);


    // entering preference phonenumber in text view
            String phonenumber = prefs.getString("phonenumber", null);
            ;
            tvphonenumber.setText(phonenumber);

    // entering preference username in text view
            String username = prefs.getString("username", null);
            ;
            tvusername.setText(username);

}
sascha
  • 265
  • 2
  • 4
  • 13
  • Pass reference to instance of hosting activity as Context to fragment when you creating it for example through your fragment constructor and then use its methods. – user3455363 Aug 27 '14 at 16:20
  • @user3455363 As I'm still a newby I'm not exactly sure how to achieve this. So I have to put `final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);` to my hosting activity and then? Sorry for my stupid question – sascha Aug 27 '14 at 16:31
  • Create field in your fragment ex. Context hostActivity; then add parameter to cunstructor of the same type - Context, and when u call new PreferencesFragment from activity in place of argument of type Context use keyword this – user3455363 Aug 27 '14 at 16:35
  • @user3455363 I don't get it :-( I did add `private Context Preferences;`and `private SharedPreferences prefs;` to my fragment and `SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);` to my host activity called Preferences but I get a null pointer exception – sascha Aug 27 '14 at 16:50

1 Answers1

11

In onActivityCreated (It's the time when the activity is created) of your fragment class, you do

Context hostActivity = getActivity();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(hostActivity);

That's how you access the hostActivity from the attached fragment.

Pierrew
  • 462
  • 5
  • 15