Android PreferenceActivity - android

I have my prefence options like this:
public class Opciones extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.opciones);
SharedPreferences sp = getPreferenceScreen().getSharedPreferences();
EditTextPreference editTextPref = (EditTextPreference) findPreference( "opcCodigo" );
editTextPref.setSummary(sp.getString("opcCodigo", ""));
EditTextPreference editTextPref2 = (EditTextPreference) findPreference( "opcUrl" );
editTextPref2.setSummary(sp.getString("opcUrl", ""));
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Preference pref = findPreference(key);
if (pref instanceof EditTextPreference) {
EditTextPreference etp = (EditTextPreference) pref;
pref.setSummary(etp.getText());
}
}
}
The fact is that when I change the data, the fields are not refreshed, I have to close the activity and launch it again to see them.
Whats I´m missing?
Thanks in advance

Implement OnPreferenceChangeListener and override the following method.
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
//newValue is the edited data
if(editTextPref == preference) editTextPref.setSummary(newValue);
else editTextPref2.setSummary(newValue);
}

Try this:
1. Add OnSharedPreferenceChangeListner
public class Opciones extends PreferenceActivity implements
OnSharedPreferenceChangeListener
2. And Override method onSharedPreferenceChanged
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,String key){
// ...
}

Related

Listening for SharedPreferences changes in MainActivity

I am trying to listen SharedPreferences changes in the MainActivity. And update the values in the settings of the app. And the working code goes like:
private SharedPreferences SP, prefs;
SharedPreferences.OnSharedPreferenceChangeListener mListener;
SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
Toast.makeText(MainActivity.this, "Key changed: "+key, Toast.LENGTH_SHORT).show();
}
};
SP.registerOnSharedPreferenceChangeListener(mListener);
But when I try to change the key value like this. It says can not resolve findPreference method. I tried doing it using context but still the error persists.
private SharedPreferences SP, prefs;
SharedPreferences.OnSharedPreferenceChangeListener mListener;
SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals("username")) {
Preference pref = findPreference(key);
pref.setDefaultValue(prefs.getString(key, "bob")); }
};
SP.registerOnSharedPreferenceChangeListener(mListener);
How can we import the method definition in MainActivity. Please tell if the way I am changing value here, if correct?
Settings.java
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.os.Bundle;
public class Settings extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
}
public static class MyPreferenceFragment extends PreferenceFragment
{
PrefManager prefManager;
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
}
preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference android:title="Your Name"
android:key="username"
android:summary="Please provide your username">
</EditTextPreference>
</PreferenceScreen>
I basically want to update the Preference in the settings page whenever SharedPreferences of key "username" is getting changed in the code.
You must implement PreferenceActivity in your activity
Add extends PreferenceActivity after your activity name and then import it's namespace:
public class MainActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
}
}
For more info look at http://developer.android.com/reference/android/preference/PreferenceActivity.html
EDITED
Use the following code:
public class Settings extends PreferenceActivity {
private SharedPreferences SP;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
SharedPreferences.OnSharedPreferenceChangeListener mListener;
SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
}
public static class MyPreferenceFragment extends PreferenceFragment implements
SharedPreferences.OnSharedPreferenceChangeListener{
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals("username")) {
Preference pref = findPreference(key);
pref.setDefaultValue(prefs.getString(key, "bob"));
}
}
}
}

Android setOnPreferenceChangeListener not being called correctly

I have a ListPreferenece in my preference screen and when It changes I need to execute a method. Problem is when I first change the preferenece list nothing happens but it works the second time round...
public static class DisplayFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
cPPreference cPBg;
cPPreference cPFt;
cPPreference cPTm;
cPPreference cPLg;
ListPreference colorThemeList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.display_preferences);
cPBg = (cPPreference) getPreferenceScreen().findPreference("ambilBg");
cPFt = (cPPreference) getPreferenceScreen().findPreference("ambilFt");
cPTm = (cPPreference) getPreferenceScreen().findPreference("ambilTm");
cPLg = (cPPreference) getPreferenceScreen().findPreference("ambilLg");
/**
* When this list changes I need to exectue a method
*/
colorThemeList = (ListPreference) getPreferenceScreen().findPreference("colorTheme");
colorThemeList.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
ThemeHandler.setTheme(cPBg, cPFt, cPTm, cPLg, colorThemeList.getValue());
return true;
}
});
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
setSummarys();
}
}
Any help greatly appreciated
O.k ...found solution
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("colorTheme")) {
ThemeHandler.setTheme(colorPickerBg, colorPickerFt, colorPickerTm, colorPickerLg, colorThemeList.getValue());
}
}
A simple check in the onSharedPreferneceChanged method :)

PreferenceFragment not saving values - with test case and screenshot

I have prepared a simple test case at GitHub for my question and have a feeling, that only few lines of code are missing to make it working.
In an Android app I have 1 activity (MainActivity.java) and 2 fragments (MainFragment.java and PrefFragment.java) - and when I change values in the preferences fragment, they are not saved.
Also the default values are not loaded and the summaries not updated:
Here is my PrefFragment where I register a shared prefs listener - in order to update the summaries - but for some reason it is never called:
public class PrefFragment extends PreferenceFragment
implements OnSharedPreferenceChangeListener {
public static final String BOOL_1 = "bool_1";
public static final String STR_1 = "str_1";
public static final String STR_2 = "str_2";
private CheckBoxPreference mBool1;
private EditTextPreference mStr1;
private EditTextPreference mStr2;
private SharedPreferences mPrefs;
private Editor mEditor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
addPreferencesFromResource(R.xml.preferences);
mBool1 = (CheckBoxPreference) findPreference(BOOL_1);
mStr1 = (EditTextPreference) findPreference(STR_1);
mStr2 = (EditTextPreference) findPreference(STR_2);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mPrefs = PreferenceManager.getDefaultSharedPreferences(activity);
mEditor = mPrefs.edit();
mPrefs.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onDetach() {
super.onDetach();
mPrefs.unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences prefs,
String key) {
Log.d("onSharedPreferenceChanged", key); // XXX is never called
if (BOOL_1.equals(key)) {
boolean bool1 = prefs.getBoolean(key, false);
mBool1.setSummary(bool1 ? "Enabled" : "Disabled");
} else if (STR_1.equals(key)) {
String str1 = prefs.getString(key, "");
mStr1.setSummary(str1);
} else if (STR_2.equals(key)) {
String str2 = prefs.getString(key, "");
mStr2.setSummary(str2);
}
}
}
And here is preference.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory
android:title="Category 1"
android:key="category_1">
<CheckBoxPreference
android:key="bool_1"
android:title="Boolean 1"
android:summary="XXX how to set this? XXX"
android:defaultValue="false" />
<EditTextPreference
android:dependency="bool_1"
android:key="str_1"
android:title="String 1"
android:summary="XXX how to set this? XXX"
android:defaultValue="change me" />
<EditTextPreference
android:dependency="bool_1"
android:key="str_2"
android:title="String 2"
android:summary="XXX how to set this? XXX"
android:defaultValue="change me too" />
</PreferenceCategory>
</PreferenceScreen>
So my question is how to handle (load, save) values in PreferenceFragment? Do I really have to extend EditTextPreference and implement onDialogClosed method in my custom class? This seems like an overkill approach to me.
Ok, the following seems to work in PrefFragment.java:
#Override
public void onResume() {
super.onResume();
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
// CHANGE 1: load saved values to set the summaries
onSharedPreferenceChanged(prefs, BOOL_1);
onSharedPreferenceChanged(prefs, STR_1);
onSharedPreferenceChanged(prefs, STR_2);
// CHANGE 2: register shared prefs listener in onResume
prefs.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
prefs.unregisterOnSharedPreferenceChangeListener(this);
}

EditTextPreference validate data before saving

I have a method to validate a EditTextPreference. My method is executed after the confirmation of data by implementing the onSharedPreferenceChanged class.
However, only occurs after you confirm the information. I would perform the check without closing the dialog box. And if ok then close or keep open for user to enter the data correctly.
If it's not possible, I would reopen the dialog box if the validation is false.
SettingsActivity.java
class SettingsActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
protected static final String TAG = "SettingsActivity";
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
SharedPreferences.Editor prefEditor = prefs.edit();
if(key.equals("pref_Url")){
String url = prefs.getString(key, "");
boolean response = (!new ConnectUtils().isConnected(this, url));
if(!response){
prefEditor.putString(key, Config.SERVER_URL_DEF_VALUE);
prefEditor.commit();
reload();
Toast.makeText(this,R.string.msgToast_server_url_invalid,Toast.LENGTH_SHORT).show();
}
}else if (key.equals("pref_Id")){
String url = Config.SERVER_URL_ID;
boolean reponse = (!new ConnectUtils().isConnected(this,url));
if(!reponse){
prefEditor.putString(key,Config.ID_DEF_VALUE);
prefEditor.commit();
reload();
Toast.makeText(Config.getContext(), R.string.msgToast_Id_invalid, Toast.LENGTH_SHORT).show();
}
}
}
private void reload(){
startActivity(getIntent());
finish();
}
}
'onPreferenceChangeListener' is a listener that is executed every time a preference is changed by the user. You can return true if data complains validation or false otherwise.
For example:
public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
findPreference("pre_mail").setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
return Pattern.matches(Constants.MAILPATTERN, (String) newValue);
}
});
}
}
Hope this help!

How to show the new value when EditTextPreference is changed

I have two PreferenceActivity in my PreferenceActivity.
My issue is when I update an item, new value is not reflected in the screen.
public class HostSettingActivity extends PreferenceActivity {
private final String MY_DEBUG_TAG = "SettingActivity";
SharedPreferences sharedPrefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(MY_DEBUG_TAG, "HostSettingActivity Started");
super.onCreate(savedInstanceState);
sharedPrefs = getPreferenceManager().getSharedPreferences();
setPreferenceScreen(createPreferenceHierarchy());
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.e(MY_DEBUG_TAG, "On Destroy");
}
private PreferenceScreen createPreferenceHierarchy() {
// Root
PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);
PreferenceCategory dialogBasedPrefCat = new PreferenceCategory(this);
dialogBasedPrefCat.setTitle("Host Settings");
root.addPreference(dialogBasedPrefCat);
EditTextPreference hostPreference = new EditTextPreference(this);
hostPreference.setKey("host");
hostPreference.setDialogTitle("Host");
hostPreference.setDefaultValue("http://example.com");
hostPreference.setSummary("Set host");
dialogBasedPrefCat.addPreference(hostPreference);
EditTextPreference portPreference = new EditTextPreference(this);
portPreference.setKey("port");
portPreference.setDialogTitle("Port");
portPreference.setDefaultValue("8080");
portPreference.setSummary("Set port");
dialogBasedPrefCat.addPreference(portPreference);
hostPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
EditTextPreference etp = (EditTextPreference) preference;
String newHostValue = newValue.toString();
Log.i(MY_DEBUG_TAG, "New Host: "+newHostValue);
etp.setText(newHostValue);
return true;
}
});
return root;
}
}
Call
preference.notifyChanged();
when its data changed and it should be redrawn.
I was confused between setText and setTitle
public boolean onPreferenceChange(Preference preference, Object newValue) {
EditTextPreference etp = (EditTextPreference) preference;
String newHostValue = newValue.toString();
Log.i(MY_DEBUG_TAG, "New Host: "+newHostValue);
etp.setTitle(newHostValue);
return true;
}
has done what I want

Categories

Resources