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
Related
can anyone tell me how can I start/stop a location service (or any other service) when a SwitchPreference in a PreferenceScreen is toggled on/of?
I'm using a settingsFragemnt (extending PreferenceFragemntCompat), which is hosted in my settings activity.
You should add OnPreferenceChangeListener which will allow you to listen switch changes:
final SwitchPreference onOffRandomColor = (SwitchPreference) findPreference(this.getResources()
.getString(R.string.sp_key_on_off_random_color));
onOffRandomColor.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object o) {
if(onOffRandomColor.isChecked()){
}else {
}
return false;
}
});
Next step is to run service:
startService(new Intent(this, LocationService.class));
my fragment looks like this:
public class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(#Nullable Bundle savedInstanceState, String rootKey){
setPreferencesFromResource(R.xml.prefs, rootKey);
// setting summaries for both list preferences ---------------------------------------------
ListPreference photo_quality = findPreference("photo_quality");
if (photo_quality != null){
photo_quality.setSummaryProvider(ListPreference.SimpleSummaryProvider.getInstance());
}
ListPreference uploads = findPreference("upload_options");
if (uploads != null) {
uploads.setSummaryProvider(ListPreference.SimpleSummaryProvider.getInstance());
}
// setting the visibility for location service ---------------------------------------------
if (!Auth.getCanDeactiveGps()){
Objects.requireNonNull(getPreferenceScreen()
.findPreference("location_category")).setVisible(false);
}
// handling locationSwitchPreference change ------------------------------------------------
SwitchPreference locationSwitch = findPreference("location");
if (locationSwitch != null){
locationSwitch.setChecked(Settings.getBoolean(Settings.DO_NOT_LOCATE,
false));
locationSwitch.setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
Settings.setBoolean(Settings.DO_NOT_LOCATE, true);
return false;
}
});
}
}
I want to evaluate checkboxpreference, tried some method from here but non of it worked. I need to get the value in the OnSharedPreferenceChangeListener, but not in PreferenceActivity. It gives an error like:
ava.lang.ClassCastException: android.app.SharedPreferencesImpl cannot be cast to android.support.v7.preference.CheckBoxPreference
Could somebody explain the problem?
sharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.d(MainActivity.this.getClass().getSimpleName(), "Einstellungen wurde geändert.");
prefsChanged = true;
if(key.equals("use_gps")) {
//TODO: CheckBox evaluate and LocationUpdate start or remove if it's not checked
CheckBoxPreference preference = (CheckBoxPreference) getSharedPreferences("use_gps", MODE_PRIVATE);
if(preference.isChecked()) {
requestLocationUpdates();
Log.d(getClass().getSimpleName(), "preference ischecked");
} else {
removeLocationUpdates();
Log.d(getClass().getSimpleName(), " preference isnotchecked");
}
}
}
};
Thanks for all the help, solution was in MAinActivity onCreate():
if(key.equals("use_gps")) {
//TODO: CheckBox auswerten udn ggfs. Standortbestimmung starten oder stoppen
boolean checkbox = sharedPreferences.getBoolean("use_gps", true);
if (checkbox == true){
Toast.makeText(MainActivity.this, "true", Toast.LENGTH_LONG).show();
requestLocationUpdates();
} else {
Toast.makeText(MainActivity.this, "false", Toast.LENGTH_LONG).show();
removeLocationUpdates();
}
}
}
This should help, instead of using OnSharedPreferenceChangeListener(), use registerOnSharedPreferenceChangeListener() to link listener to the any of your preference outside of the Preference an
Code snippet for the non-preference Activity where you want to attach the listener for a preference:
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener()
{
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
Log.v("CHANGE ", "YES");
boolean use_gps_stat = sharedPreferences.getBoolean("use_gps", true);
if(key == "use_gps")
{
Toast.makeText(getApplicationContext(), "Changed", Toast.LENGTH_LONG).show();
if(use_gps_stat)
{
Toast.makeText(getApplicationContext(), "Checked", Toast.LENGTH_LONG).show();
requestLocationUpdates();
Log.d(getClass().getSimpleName(), "preference ischecked");
}
else
{
Toast.makeText(getApplicationContext(), "Unchecked", Toast.LENGTH_LONG).show();
removeLocationUpdates();
Log.d(getClass().getSimpleName(), " preference isnotchecked");
}
}
}
});
In your preference activity add this to overriden onCreate:
bindPreferenceSummaryToValue_CheckBox(findPreference("use_gps"));
So it should look like this:
public static class MainPreferenceFragment extends PreferenceFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
bindPreferenceSummaryToValue_CheckBox(
findPreference("use_gps"));
.
.
.
And add bindPreferenceSummaryToValue_CheckBox outside onCreate:
private static void bindPreferenceSummaryToValue_CheckBox(Preference preference)
{
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getBoolean(preference.getKey(), true));
}
For sBindPreferenceSummaryToValueListener simply add to the class extending to AppCompatPreferenceActivity:
private static Preference.OnPreferenceChangeListener
sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener()
{
#Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
//Do something on prefernce change.
return true;
}
};
I recently tried this code structure and worked, if there are any queries let me know down in the comments.
I have two Listprefence in a preference fragment and I want to refresh second Listpreference values when in first is selected something.
The Listpreferences are filled over the internet.
public class array extends PreferenceFragment {
public static String apref;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
final ListPreference array1Preference = (ListPreference)findPreference("array1");
setArray1PreferenceData(array1Preference);
array1Preference.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
setArray1PreferenceData(array1Preference);
return true;}});
final ListPreference array2Preference = (ListPreference)FindPreference("array2");
setArray2PreferenceData(array2Preference);
array2Preference.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
setArray2PreferenceData(array2Preference);
return true;}});
}
public void setArray1PreferenceData(ListPreference array1Preference) {
new LoadArray1().execute();
}
public void setArray2PreferenceData(ListPreference array2Preference) {
String CPref = "array1";
SharedPreferences prefs = this.getActivity().getSharedPreferences(
"com.asdd.ck_preferences", Activity.MODE_PRIVATE);
apref = prefs.getString(CPref, "");
if (apref != "0") {
new LoadArray2().execute();
} else {
new LoadArray1().execute();
}
}
public class LoadArray1 extends AsyncTask<String, String, String> {
}
public class LoadArray2 extends AsyncTask<String, String, String> {
}
}
Finally I have got the answer my self.
array1Preference
.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
apref = (String) newValue;//Sets the new value for second list loader (LoadArray2)
PreferenceManager.getDefaultSharedPreferences(getActivity()).edit().putString(key, "0").commit();//Clear in the preference file the 2nd listpreference selection data.
setArray2PreferenceData(array2Preference);//Reload data from server
array2Preference.setValue("0");//When in 1st selected something clear in 2nd the selection.
return true;
}
});
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!
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){
// ...
}