How to get preference value in preference fragment
I want to show the preference value in the user settings screen. To do this, I need to get the values, in this case strings, in the preference snippet. In non fragments (actions) I get values, eg. final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
and get the string with String phonenumber = prefs.getString("preference_name", null);
, but in the preference fragment is getDefaultSharedPreferences
not applicable for the preference fragment.
Any idea how to solve this?
Here is 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);
}
source to share
In the onActivityCreated (This is the time the activity is created) of your fragment class, you
Context hostActivity = getActivity();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(hostActivity);
This is how you access hostActivity from the attached snippet.
source to share