Access text of EditTextPreference from Fragment - android

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, call getDefaultSharedPreferences(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:
Option 1 - Use the default SharedPreferences to retrieve the saved value
It'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");
Option 2 - Set your PreferenceFragment to use named shared prefs
You 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
}

Related

add specific named SharedPreferences from resource in PreferenceActivity or PreferenceFragment

If I have a Preference-Activity or -Fragment I can provide a preference.xml file to build my PreferenceScreen and show it via addPreferenceFromResource(R.xml.preference)
Changed values can then be retrieved by PreferenceManager.getDefaultSharedPreferences(Context)
I'm just wondering if it is possible to take other than the default Preferences for my Fragment.
I want to have a PreferenceFragment that is able to store its Preferences (provided via xml) in Preferences I can retrieve via context.getSharedPreferences("customPrefName", Context.MODE_PRIVATE)
but I couldn't find something in the xml like
<PreferenceScreen android:prefName="customPrefName">...
If you want to have a custom preference xml file, you need to set preference name before adding it to screen from xml in your PreferenceFragment class.
public class CustomNamePreferenceFragment extends PreferenceFragment {
private static final String PREF_FILE_NAME = "custom_name_xml";
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PreferenceManager preferenceManager = getPreferenceManager();
preferenceManager.setSharedPreferencesName(PREF_FILE_NAME);
addPreferencesFromResource(R.xml.prefs);
... //rest of the code
}
}
Note : You need to set shared preference name just after the super call of onCreate() and before calling addPreferencesFromResource() method.

Confused on Reading SharedPreferences Without a PreferenceActivity

Because I want an AppCompat Action Bar on all of my settings submenus, I had to implement a workaround and my Settings Activity extends AppCompatActivity, not PreferenceActivity. I'm using a PreferenceFragment in the activity to handle the preferences, and each PreferenceScreen has its own xml file, which the PreferenceFragment switches out for each submenu in the settings. All of this was necessary to get the Action Bar to stay put through all of my submenus.
I'm trying to read a string value from the shared preferences file from within my MainActivity, and I've tried three different methods for getting that information, none of which have worked:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String btSelectPref = sharedPref.getString(getString(R.string.bt_select_key), "");
,
SharedPreferences sharedPref = getSharedPreferences(name, MODE_PRIVATE);
String btSelectPref = sharedPref.getString(getString(R.string.bt_select_key), "");
and
SharedPreferences sharedPref = getPreferences(MODE_PRIVATE);
String btSelectPref = sharedPref.getString(getString(R.string.bt_select_key), "");
Here is the relevant section of my preferences.xml:
<PreferenceCategory
android:title="Bluetooth"
android:key="pref_bt">
<Preference
android:title="Select Bluetooth Device"
android:key="#string/bt_select_key"
android:defaultValue="0">
</Preference>
</PreferenceCategory>
This should fill the btSelectPref string with a "0", but it's always empty when I test it. I have included PreferenceManager.setDefaultValues(this, R.xml.preferences, false); in onCreate in my MainActivity, so the default values should be set.
I'm not sure which of these methods I should be using since I have multiple resource files for my settings, but none of them seem to be working for me. In the case of getSharedPreferences(name, MODE_PRIVATE), I have no idea what the name parameter should be referencing, since I've never named my shared preferences file.
EDIT: It turns out my issue was not related to getting values from the shared preferences file. I just had the wrong xml tag on the preference I was trying to check the value of. I changed it from a generic <Preference> tag to a <ListPreference> and my code started working with PreferenceManager.getDefaultSharedPreferences().
What you want to do and what you are doing differs. If you just want to put default shared preference for a key then consider this example. If your whole activity has just one shared pref file then you need not specify any name. It will automatically get it.
public MainActivity extends AppCompatActivity {
SharedPreferences mPrefs;
int test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_counter);
mPrefs = this.getPreferences(Context.MODE_PRIVATE);
test = mPrefs.getInt("pref_bt_select", 0);}
}
For the above example you can define the key and default value in your strings.xml and then you can refer to it while looking for the prefs you want.
Hey I have used AppCompat for my preference screen too.I did this because I wanted to use Vintage Chroma and this was the only way. But I am able to use PreferenceManager.getDefaultSharedPreference() without any errors.
Also if you want to use default shared preferences in the Fragment you can use :
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
Here is my full code :
public class PreferencesActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager()
.beginTransaction()
.replace(android.R.id.content, new PreferencesScreen())
.commit();
ActionBar toolbar = getSupportActionBar();
if (toolbar != null) {
toolbar.setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
public static class PreferencesScreen extends PreferenceFragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings_xml);
}
}
}
Here is my code snippet for MAinActivity
Just the initial part where I set the default text theme.
`public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
AutoCompleteTextView mytextview;
public static String[] list;
ArrayList<String> recent = new ArrayList<String>();
public int recent_index = 0;
Menu mMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
/*Setting default theme.*/
SharedPreferences Sp= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
int firstRun=Sp.getInt("firstRun",0);
if(firstRun==0)
{
SharedPreferences.Editor editor=Sp.edit();
editor.putInt("paragraphFontColor", Color.parseColor("#ffffff"));
editor.putInt("headingFontColor",Color.parseColor("#DE5246"));
editor.putInt("subheadingFontColor",Color.parseColor("#597d5e"));
editor.putInt("hyperlinksFontColor",Color.parseColor("#A5D8F5"));
editor.putInt("bodyColor",Color.parseColor("#2b2b2b"));
editor.putString("paragraphFont","PrintClearly.otf");
editor.putString("headingFont","PrintBold.otf");
editor.putString("subheadingFont","PrintBold.otf");
editor.putString("hyperlinkFont","PrintBold.otf");
editor.putString("paragraphFontStyle","normal");
editor.putString("headingFontStyle","normal");
editor.putString("subheadingFontStyle","normal");
editor.putString("hyperlinkFontStyle","normal");
editor.putString("actionBarColor","#597d5e");
editor.putString("paragraphFontSize","20px");
editor.putString("headingFontSize","30px");
editor.putString("subheadingFontSize","20px");
editor.putString("hyperlinkFontSize","20px");
editor.putString("firstRun",0);
editor.commit();
}
`

SharedPreferences are being restored as defaults in onResume instead of the saved SharedPreferences values

I have a PreferenceActivity P that stores values to SharedPreferences. This is working--I am able to make selections from the lists and the summary values are displayed correctly.
The problem is when I attempt to access the SharedPreference values within Activity A. The default values are loaded instead of the stored values. Only after I access the PreferenceActivity from Activity A do the up-to-date SharedPreference values become available to Activity A. Any suggestions on how to resolve this? Is there any option to using PreferenceManager.getDefaultSharedPreferences?
Here is the bulk of the PreferenceActivity code (I omitted the onSharedPreferenceChanged listener for brevity):
public class P extends PreferenceActivity {
public static String KEY_PREF_show_watch_areas, KEY_PREF_time_format, KEY_PREF_date_format;
String PREF_show_watch_areas, PREF_time_format, PREF_date_format;
static SharedPreferences sharedPrefs;
Preference pref_show_watch_areas=null;
ListPreference pref_time_format=null, pref_date_format=null;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPrefs = PreferenceManager.getDefaultSharedPreferences( getApplicationContext() );
KEY_PREF_show_watch_areas = getString(R.string.key_pref_show_watch_areas);
KEY_PREF_time_format = getString(R.string.key_pref_time_format);
KEY_PREF_date_format = getString(R.string.key_pref_date_format);
PREF_show_watch_areas = getString(R.string.pref_show_watch_areas);
PREF_time_format = getString(R.string.pref_time_format);
PREF_date_format = getString(R.string.pref_date_format);
//Load up the preference items (from XML)
addPreferencesFromResource(R.xml.preferences);
//DATE pref
pref_date_format = (ListPreference) findPreference(KEY_PREF_date_format); //Set summary to user selected value
pref_date_format.setSummary(pref_date_format.getEntry() );
//TIME pref
pref_time_format = (ListPreference) findPreference(KEY_PREF_time_format); //Set summary to show user selected value
pref_time_format.setSummary(pref_time_format.getEntry());
}
} // [END P]
Here is the onResume in Activity A:
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPrefsResume = PreferenceManager.getDefaultSharedPreferences(getApplicationContext() );
dateFormatPref = sharedPrefsResume.getString(P.KEY_PREF_date_format, "d-MMM-yy");
timeFormatPref = sharedPrefsResume.getString(P.KEY_PREF_time_format, "h");
} // [END onResume]
I've discovered and resolved the problem. I was trying to access the SharedPrefs values with uninitialized variables (e.g., P.KEY_PREF_date_format). That's the reason the default values were being returned. I've now moved the static variables to my MainActivity to ensure they are initialized. Voila. SharePreferences are working as expected now.

Setting sharedPreferences default values

I have an application where I'm setting roughly around 200 shared preferences when the application is run for the first time. I was initially loading all the preferences by calling it from my onCreate method
SharedPreferences pref = getSharedPreferences(CALC_PREFS, MODE_PRIVATE);
settingsEditor = prefs.edit();
settingsEditor.putString("Something", "");
....
settingsEditor.commit();
and it would work well and rather quickly. I then redesigned my application to have an abstract activity class to handle all the work with the shared preferences becacuse I have 4 different activities accessing these preferences.
public abstract class AnActivity extends Activity{
// Shared Preference string
private static final String CALC_PREFS = "CalculatorPrefs";
// Editor to customize preferences
private Editor settingsEditor;
// Shared preference
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
prefs = getSharedPreferences(CALC_PREFS, MODE_PRIVATE);
settingsEditor = prefs.edit();
}
protected void addPref(String key, String value){
settingsEditor.putString(key, value).commit();
}
protected void addPref(String key, int value){
settingsEditor.putInt(key, value).commit();
}
//other methods were not posted
}
My main activity not extends the "AnActivity" class. However, when I run my application on a fresh install or attemp to access any shared preference, it takes upwards of 10 seconds to instantiate everything.
How can I set the default values in a clean and efficient manner? Does creating an Abstract class to handle the preferences create more overhead than just calling getSharedPreferences manually?
Are you commiting each time you add a preference? This is probably your issue, commiting for each entry could be quite expensive, batch together your put's and commit once.
If you don't need to specify the default value, you could always use clear() instead
http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#clear%28%29

How can I call the Preferences with the new values?

I use some CheckBoxPreferences, but they are not indepentent. That means, wenn I change one CheckBoxPreference, others are fixed. I use the following code:
public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
Context context = getApplicationContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPrefs, String key) {
SharedPreferences.Editor editor = sharedPrefs.edit();
if ((key.equals("A")) & (key.equals("B"))) {
editor.putBoolean("C", true);
editor.commit();
}
}
}
After this the CheckBoxPreference "C" has a new value, but I can't see it. How can I update the screen with the new values?
By using a subclass of PreferenceActivity you do not have to handle the updating of the preferences UI. You define the preferences in the resource file loaded by addPreferencesFromResource() and the Activity will be rendered accordingly. Changes will be persisted automatically and should be visible immediately. You do not have to register your preferences Activity as a SharedPreferences.OnSharedPreferenceChangeListener.
When onSharedPreferenceChanged() is called the new value is already saved to the preferences.
This notification is for other Activities than the subclasses of PreferenceActivity. To know how to access the saved preferences you need to look at the file in res/xml/settings.xml it should contain android:key attributes. The attribute values give you the key to the preference.
You can retrieve the value via the following:
PreferenceManager.getDefaultSharedPreferences(aContext).getString(key, "");

Categories

Resources