How can I call the Preferences with the new values? - android

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, "");

Related

Access text of EditTextPreference from Fragment

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
}

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

Android Properties not updating after editing and committing

in the onCreate method of my PreferenceActivity i set some Properties like this:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("pref_mykey", true);
editor.commit();
It seems to work but the View is not updating so when i open the properties the onCreate runs and changes the values. I will then see the "old" values on the Screen until i close and reopen the prefs screen, then i do see the new properties.
I already tried this after the commit:
((BaseAdapter) getPreferenceScreen().getRootAdapter()).notifyDataSetChanged();
But without any effect. I still see the "old" Prefs until i close and reopen the PreferenceActivity .
What am i doing wrong? How can i refresh the PreferenceActivity after setting values in the onCreate method?
Thanks a lot for your help.
This was buggin me all day but finally found a solution.
((ListPreference)getPreferenceScreen().findPreference("key_of_preference_in_xml_file")).setValue(code);
Your example is with a boolean so it'll have to change based on what kind of preference it is.
IE:
((CheckBoxPreference)getPreferenceScreen().findPreference("key_of_preference_in_xml_file")).setChecked(true);
If you use a PreferenceFragment than you need to inject the PreferenceScreen in the activity.
public class SettingsActivity extends Activity implements ScanFragment.OnFragmentInteractionListener {
private PreferenceScreen prefScreen;
public void setPreferenceScreen(PreferenceScreen prefScreen){
this.prefScreen = prefScreen;
}
#Override
public void onFragmentInteraction(String scanContent) {
// commiting to editor retrieved from preference manager would not refresh view
EditTextPreference pref = (EditTextPreference)this.prefScreen.findPreference(getString(R.string.preference_url_key));
pref.setText(scanContent);
}
public static class SettingsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
((SettingsActivity)this.getActivity()).setPreferenceScreen(this.getPreferenceScreen());
}
}
}

How to update internal values of a PreferenceActivity when SharedPreferences change

I use a Preference in a PreferenceActivity to load default values: when this specific Preference is clicked, something like this happens:
private String mResetKeys = "key1,key2,key3";
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor prefs_editor = prefs.edit();
for (String current_pref : mResetKeys.split(",")) {
prefs_editor.remove(current_pref);
}
prefs_editor.commit();
But afterwards, the Preferences whose corresponding SharedPreference was reset still show the old value - it seems to be cached in the Preference. Only when I leave the PreferenceActivity and reopen it, the Preferences show the new values.
How can I update the PreferenceActivity programmatically?
I had a similar problem. This probably isn't the most correct fix but it worked for my purposes. Right after I did the commits, I called the Activity.recreate(); method.
The activity will restart (onDestroy()/onCreate()/etc) but for my purposes all I needed was a special handling on one preference. I listened for a certain preference with an OnPreferenceClickListener and made an alert dialog box with a kind of warning message and an option to change their mind. If they did want to change their mind, I did my commit of the new value to the preference activity and then called recreate() so that the checkbox preference would be updated.
However, I am also interested in a way to do this without recreating the activity...
Update preference value without reloading PreferenceActivity
from http://liquidlabs.ca/2011/08/25/update-preference-value-without-reloading-preferenceactivity/
Here is how to update default shared preference value of target element (in this case EditTextPreference)
public class YourCustomPreference extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
// some logic goes above, when you want to reset value and update EditTextPreference value
// For convenience, I am going to wrap two different task in different methods
private void resetPreferenceValue() {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
SharedPreferences.Editor prefEditor = sharedPref.edit(); // Get preference in editor mode
prefEditor.putString("your_edit_text_pref_key", "DEFAULT-VALUE"); // set your default value here (could be empty as well)
prefEditor.commit(); // finally save changes
// Now we have updated shared preference value, but in activity it still hold the old value
this.resetElementValue();
}
private void resetElementValue() {
// First get reference to edit-text view elements
EditTextPreference myPrefText = (EditTextPreference) super.findPreference("your_edit_text_pref_key");
// Now, manually update it's value to default/empty
myPrefText.setText("DEFAULT-VALUE"); // Now, if you click on the item, you'll see the value you've just set here
}
}

Categories

Resources