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);
}
To inflate from XML, use the addPreferencesFromResource(int) . The root element should be a PreferenceScreen . Subsequent elements can point to actual Preference subclasses. As mentioned above, subsequent PreferenceScreen in the hierarchy will result in the screen break.
In Android apps, there are often settings pages that contain different options the user can tweak. The PreferenceFragment and PreferenceFragmentCompat contains a hierarchy of preference objects displayed on screen in a list. These preferences will automatically save to SharedPreferences as the user interacts with them.
androidx.preference.PreferenceScreen. A top-level container that represents a settings screen. This is the root component of your Preference hierarchy. A PreferenceFragmentCompat points to an instance of this class to show the preferences. To instantiate this class, use PreferenceManager.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With