I've got a Preferenceactivity with a EditTextPreference.
What I'm looking for is the command to access the inserted text of the EditTextPreference from a fragment.
What I have so far:
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
String name = preferences.getString("edit_text_preference_name", "Default");
I allways get "Default" instead of my actual inserted text from the EditTextPreference.
Thanks in Advance.
Edit:
from SettingsActivity.java
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class BarcodePreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_barcode);
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(findPreference("edit_text_preference_barcode"));
bindPreferenceSummaryToValue(findPreference("edit_text_preference_name"));
}
}
pref.xml
<EditTextPreference
android:capitalize="words"
android:defaultValue="@string/pref_default_display_name"
android:key="edit_text_preference_name"
android:maxLines="1"
android:selectAllOnFocus="true"
android:singleLine="true"
android:title="@string/pref_default_display_name" />
From the documentation of PreferenceFragment
:
To retrieve an instance of
SharedPreferences
that the preference hierarchy in this fragment will use, callgetDefaultSharedPreferences(android.content.Context)
with a context in the same package as this fragment.
This means that the PreferenceFragment
saves the values to the default shared preferences which leaves you two options:
SharedPreferences
to retrieve the saved valueIt's pretty simple, you need to call the PreferenceManager
's getDefaultSharedPreferences(...)
static method to access the default shared prefs. So instead of
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
String name = preferences.getString("edit_text_preference_name", "Default");
do
// use getActivity() instead of getContext() if you're using the framework Fragment API and min SDK is lower than 23
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getContext());
String name = preferences.getString("edit_text_preference_name", "Default");
PreferenceFragment
to use named shared prefsYou can set the name of the used shared prefs in your BarcodePreferenceFragment
's onCreate(...)
method by calling setSharedPreferencesName(...)
on the belonging PreferenceManager
:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPreferenceManager().setSharedPreferencesName("pref");
// the rest of your code
}