onSharedPreferenceChanged without using getDefaultSharedPreferences - android

I'm using context.getSharedPreference instead of getDefaultSharedPreferences.
Means :
SharedPreferences checkboxSetting = context.getSharedPreferences(
"myPreferenceDB", Context.MODE_PRIVATE);
boolean flag = checkboxSetting.getBoolean("checkboxKey",true);
And preference.xml :
<CheckBoxPreference
android:key="checkBoxPrefff"
android:title="#string/title"
android:defaultValue="true"/>
Application setting has a checkboxpreference that I want to get the value of, checked or not checked.
Will this work?
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equalsIgnoreCase("checkBoxPrefff")) {
sharedPreferences.getBoolean(key,true);
}
}
Does sharedPreferences use default database ( ..._preference.xml ) or my defined database ( "myPreferenceDB" )?
Does key is "checkboxKey" or is null?
Because when I want to get value like
SharedPreferences temp = context.getSharedPreferences(
"myPreferenceDB", Context.MODE_PRIVATE);
boolean flag = temp.getBoolean("checkboxKey",true);
it's wrong and gets back defValue (true) . But when use like
SharedPreferences temp = PreferenceManager.getDefaultSharedPreferences(context);
boolean flag = temp.getBoolean("checkboxKey",true);
it works.

Once again I would like to mention sharedPref is not a DB but rather an XML file. I hope you are looking for the following code.
public class SettingsActivity extends PreferenceActivity {
/*
* (non-Javadoc)
*
* #see android.preference.PreferenceActivity#onCreate(android.os.Bundle)
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPreferenceManager().setSharedPreferencesName("myPref");
addPreferencesFromResource(R.xml.pref);
}

You can register a SharedPreferenceChangedListener on any shared pref that you are using. It need not be the default shared preference.
getApplicationContext().getSharedPreferences("myPreferenceDB", 0).registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
}
});

Related

Loading up value from SharedPreferences

In my Application class, I have the following:
public void loadPrefs(){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Boolean soundValue = sharedPrefs.getBoolean("SOUND", false);
}
public void savePrefs(String key, boolean value){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = sharedPrefs.edit();
edit.putBoolean(key, value);
edit.commit();
}
All OK there as far as I can tell.
Now in my main class which extends SurfaceView, I have the following:
myApp mySettings = (myApp)getContext().getApplicationContext();
Then I can save values like so: (Again from my surfaceView activity)
myPlanSettings.savePrefs("SOUND", false);}
However, what I just cannot work out is how to read the value back so I can set a local variable like so:
Boolean thisValue = (the value from the shared preferences).
Thanks for any help
Try this
public Object loadPrefs(String key,String defaul){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
return sharedPrefs.get(key,default);
}
Cast it with the type while using getting the value
Basic usage:
boolean b=(Boolean)loadPrefs("value","default value")

Checking an editText that is on the Shared prefs settings screen

I want to know if there is a way to check what someone is entering on the shared prefs/settings screen for validation. The user touches the Ip enter options, an edittext dialog pops up and I am trying to restrict what they can enter to something like a standard IP address(ie. 0-255.0-255.0-255.0-255) I have looked in numerous online forums and saw examples of different things with REGEX and patterns and this is what I have so far, but absolutely nothing is happening....Can anyone help me out? I would greatly appreciate it!
public class PrefsActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener
{
private EditTextPreference ipTextBox;
private String whatWasTyped;
private String previousText = "";
private Editor myEditor;
final Pattern IP_ADDRESS = Pattern
.compile("^((1\\d{2}|2[0-4]\\d|25[0-5]|\\d?\\d)\\.){3}(?:1\\d{2}|2[0-4]\\d|25[0-5]|\\d?\\d)$");
private String IP_FROM_PREFS = "ipAddressPref";
SharedPreferences prefs;
#Override
/**
* The onCreate method handles thing when starting this activity,
* mainly display the activity_settings.xml.
*/
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// pattern for IP address validation
addPreferencesFromResource(R.layout.activity_settings);
// prefs.registerOnSharedPreferenceChangeListener(this);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
// Get a reference to the preferences
ipTextBox = (EditTextPreference) getPreferenceScreen().findPreference(
IP_FROM_PREFS);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key)
{
// check prefs value for IP.
if (key.equals(IP_FROM_PREFS))
{
whatWasTyped = prefs.getString(IP_FROM_PREFS, "");
CharSequence s = whatWasTyped;
if (IP_ADDRESS.matcher(s).matches())
{
previousText = s.toString();
myEditor = prefs.edit();
myEditor.putString(IP_FROM_PREFS, previousText);
myEditor.commit();
} else
{
//if the format does not match, put up an error message
// or something.
}
}
}
#Override
protected void onResume()
{
super.onResume();
// Setup the initial values
// mCheckBoxPreference.setSummary(sharedPreferences.getBoolean(key,
// false) ? "Disable this setting" : "Enable this setting");
// mListPreference.setSummary("Current value is " +
// sharedPreferences.getValue(key, ""));
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
previousText = prefs.getString(IP_FROM_PREFS, "");
}
#Override
protected void onPause()
{
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
}
Since this is something created on the shared prefs screen, there are no button id, etc...
Just writing
whatWasTyped.replace(s, previousText);
will not assign the the previousText to the SharedPreference you need to assign it back to the shared preference and commit.

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

Android: updating displayed preferences from SharedPreferences

I'm writing an android app with a preferencesActivity in which selections made in my instance of preferencesActivity affect the values of other preferences items displayed. While I'm able to change the values of the underlying SharedPreferences items pogrammatically, those changed values aren't reflected in the displayed list items until I exit my preferencesActivity and reload it. Below is a stripped down version of my settings class and xml file which illustrate the problem. If a user sets Guitar as the value for the preference with the key instrumentList, I'd like the preference with key tuningChoice to revert to Standard.
//necessary import declarations go here
public class Settings extends PreferenceActivity implements OnSharedPreferenceChangeListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
app_preferences.registerOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged (SharedPreferences sharedPreferences, String key) {
Log.d("onSharedPreferencesChanged", "sharedPreferences changed. key: " + key);
Editor preferencesMod = sharedPreferences.edit();
String instrumentChoice = sharedPreferences.getString("instrumentList", "Guitar");
if(key.equals("instrumentList")) {
Log.d("Settings", "key is instrumentList. chooseTuning before if: " + sharedPreferences.getString("chooseTuning", "no luck"));
if(instrumentChoice.equals("Guitar")) {
preferencesMod.putString("chooseTuning", "Standard");
preferencesMod.commit();
Log.d("Settings", "chooseTuning after if: " + sharedPreferences.getString("chooseTuning", "ciao"));
}
}
}
}
xml file preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:title="Settings">
<ListPreference android:title="Choose an Instrument" android:key="instrumentList" android:entryValues="#array/instruments" android:entries="#array/instruments"/>
<ListPreference android:title="Choose Tuning" android:key="chooseTuning" android:entryValues="#array/tuningChoices" android:entries="#array/tuningChoices" android:persistent="true"/>
</PreferenceScreen>
I can call addPreferencesFromResource again in my onSharedPreferenceChanged method and that loads a duplicate of all the preferences items, displayed below the old items, with the correct values. If I could figure out some way to cancel out the initial addPreferencesFromResource called during onCreate, I guess I would be set.
Any help would be appreciated, Thanks
I do something along these lines...hopefully it helps:
ListPreference list = (ListPreference) getPreferenceManager().findPreference("myList");
list.setValue(sharedPrefs.getString("myList", "default"));
list.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
sharedPrefs.put("myList", newValue.toString());
return true;
}
});
You need to prevent addPReferencesFromResource from running twice? Is this loading your default values? If so, add an additional SharedPreference called DEFAULTS_LOADED and read its value in on create like: (WARNING PSUEDO CODE):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean loadDefaults = app_preferences.getBoolean(DEFAULTS_LOADED, true);
if(loadDefaults)
{
addPreferencesFromResource(R.xml.preferences);
Editor editor = app_preferences.edit();
editor.putBoolean(DEFAULTS_LOADED, true);
editor.commit();
}
app_preferences.registerOnSharedPreferenceChangeListener(this);
}
This will prevent you defaults from being written to the shared preferences every time your activity starts. I assume this is at least a portion of your issue.
If anyone comes to this problem, this is the solution:
ListView list = preferenceActivity.getListView();
list.performItemClick(list, 1, list.getItemIdAtPosition(1));
Maybe I am too late for answering this. But, I hope this might help beginner like me.
PackageInfo packageInfo = null;
try {
packageInfo = preference.getContext().getPackageManager().getPackageInfo(preference.getContext().getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
preference.setSummary(packageInfo.versionName);

Setting UI preference Summary field to the value of the preference

New to Android, I have some code when the user changes a preference I update the Summary field in the UI preference to be the value they entered. However, when the preference activity is created I'd like to set the Summary fields to be the values in the corresponding preferences.
Please advise. Thanks.
public class MyPreferenceActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
SharedPreferences sp = getPreferenceScreen().getSharedPreferences();
sp.registerOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
Preference pref = findPreference(key);
if (pref instanceof EditTextPreference) {
EditTextPreference etp = (EditTextPreference) pref;
pref.setSummary(etp.getText());
}
}
}
I am new too so may not be the best code but this is similar to what I am doing. You probably want to register you listener onResume and unregister it onPause though rather than onCreate. I hope this helps.
Mainly you just need to grab the pref, the pref value and set the summary.
public class MyPreferenceActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
SharedPreferences sp = getPreferenceScreen().getSharedPreferences();
EditTextPreference editTextPref = (EditTextPreference) findPreference("thePrefKey");
editTextPref
.setSummary(sp.getString("thePrefKey", "Some Default Text"));
}
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
Preference pref = findPreference(key);
if (pref instanceof EditTextPreference) {
EditTextPreference etp = (EditTextPreference) pref;
pref.setSummary(etp.getText());
}
}
}
This worked for me.
public class PrefsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener
{
private Preference pref;
private String summaryStr;
String prefixStr;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
SharedPreferences sharedPref = getPreferenceScreen().getSharedPreferences();
sharedPref.registerOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
//Get the current summary
pref = findPreference(key);
summaryStr = (String)pref.getSummary();
//Get the user input data
prefixStr = sharedPreferences.getString(key, "");
//Update the summary with user input data
pref.setSummary(summaryStr.concat(": [").concat(prefixStr).concat("]"));
}
}
What I usually do is:
1 - Make a new class which extends the kind of preference I need to show (1 per preference type)
2 - Inside its code, do the appropriate actiob to show the updated summary
3 - Refer this class in the res/xml/preferences.xml file
Let me swo a small example, good for an EditTextPreference:
CLS_Prefs_Edit.java
/**
* CLS_Prefs_Edit class
*
* This is the class that allows for a custom EditTextPrefence
* (auto refresh summary).
*
* #category Custom Preference
* #author Luca Crisi (luca.crisi.lc#gmail.com)
* #copyright Luca Crisi
* #version 1.0
*/
package com.your_name.your_app;
/* -------------------------------- Imports --------------------------------- */
import android.content.Context;
import android.preference.EditTextPreference;
import android.util.AttributeSet;
public final class CLS_Prefs_Edit
extends EditTextPreference
{
/* ---------------------------- Constructors ---------------------------- */
public CLS_Prefs_Edit(final Context ctx, final AttributeSet attrs)
{
super(ctx, attrs);
}
public CLS_Prefs_Edit(final Context ctx)
{
super(ctx);
}
/* ----------------------------- Overrides ------------------------------ */
#Override
public void setText(final String value)
{
super.setText(value);
setSummary(getText());
}
}
res/xml/preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
>
<PreferenceCategory android:title="#string/pref_phone_cat">
<!-- NORMAL EditTextPreference, NO summary update -->
<!-- <EditTextPreference -->
<!-- android:widgetLayout="#layout/arr_dn" -->
<!-- android:key="phone" -->
<!-- android:title="#string/pref_phone_title" -->
<!-- android:summary="#string/pref_phone_summ" -->
<!-- android:defaultValue="" -->
<!-- android:inputType="phone" -->
<!-- android:digits="+1234567890" -->
<!-- /> -->
<!-- MY EditTextPreference, WITH summary update -->
<com.your_name.your_app.CLS_Prefs_Edit
android:widgetLayout="#layout/arr_dn"
android:key="phone"
android:title="#string/pref_phone_title"
android:summary="#string/pref_phone_summ"
android:defaultValue=""
android:inputType="phone"
android:digits="+1234567890"
/>
</PreferenceCategory>
</PreferenceScreen>
Of course, set your strings in /res/values/strings, and you're done.
Note that this solution works for both PreferenceFragments and PreferenceActivities.
I'm using it for an app tha runs on 2.2 Froyo (showing a PreferenceActivity) as well as on 4.4 KitKat (showing a PreferenceFragment)
I hope it helps.
First, for your class:
class SettingsFragment : SettingsBaseFragment(),
// Make sure you implement the OnSharedPreferenceChangeListener
SharedPreferences.OnSharedPreferenceChangeListener,
Preference.OnPreferenceClickListener {}
Next, in the onSharedPreferenceChanged, you have a reference to the sharedPreference, which you can use to get the preference result. Then you can use the latest result you get to alter the summary:
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
when (key) {
SETTINGS_AUTO_SETTLEMENT -> refreshSummaryForAutoSettlement(sharedPreferences?.getBoolean(SETTINGS_AUTO_SETTLEMENT, false))
}
}
// helper function for altering the summary for the preference
private fun refreshSummaryForAutoSettlement(isAutoSettlementEnabled: Boolean?) {
when (isAutoSettlementEnabled != null && isAutoSettlementEnabled) {
true -> findPreference(SETTINGS_AUTO_SETTLEMENT).summary = getString(R.string.auto_settlement_enabled_summary)
false -> findPreference(SETTINGS_AUTO_SETTLEMENT).summary = getString(R.string.auto_settlement_disabled_summary)
}
}

Categories

Resources