I am tring to create a sharedpreference to save some authentication info to a third party service. In my preferences.xml there is a login and password fields but i would like to check if the values are valid (authenticate) when edited. What would be a good approach?
So far, i have this:
on create
findPreference("sync_service_enabled").setOnPreferenceChangeListener(this);
findPreference("sync_service_user").setOnPreferenceChangeListener(this);
findPreference("sync_service_pwd").setOnPreferenceChangeListener(this);
my listener
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference.getKey().contains("sync_service")){
new AuthenticationRemoteAsyncTask(this.getActivity(), user, password, service).execute();
}
return true;
I also need to save a token generated by the remote service so I need to wait for the aynstask to be finished.
Any sugestion?
I resolved my problem criating a custom dialogpreference. I Replaced the positive button onclicklistener so it dont close the dialog automatically and start my remote task. The asynctask will notify my preferencedialog after success and only then I close the dialog.
CODE
#Override
protected void showDialog(Bundle state) {
super.showDialog(state);
...
positiveButton.setOnClickListener(this);
negativeButton.setOnClickListener(this);
}
onclick handler
public void onClick(View view){
this.result = null;
if(view.getId() == positiveButton.getId()) {
String password = textPassword.getText().toString();
String user = textLogin.getText().toString();
new AuthenticationTask(getContext(),user, password)
.notify(this).execute();
}else{
alertDialog.dismiss();
}
}
check the result before close
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (result != null) {
SharedPreferences.Editor editor = getEditor();
editor.putString("sync_service_token",result);
editor.commit();
}
}
AuthenticationTask is a custom class that wrapp all the async stuff and call a notify method.
Related
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 DialogPreference dialog instance. How can i register an listener on onDialogClosed. I want when Ok button is clicked to execute some code.
Is this possible to do with instance of DialogPreference ?
I know I can do it like
#Override
protected void onDialogClosed(boolean positiveResult) {
if (positiveResult) {
String text=MyEditText.getText();
}
else {
// cancel hit
}
}
but i am not extending DialogPreference. i have just instance of it.
Use preference.getDialog().setOnDismissListener(listener);
If you have the instance of DialogPreference, then you can impement onPreferenceChangedListener for the DialogPreference.
myDialogPreference
.setOnPreferenceClickListener(
new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(
Preference preference) {
// Your code here
});
I have PrefActivity and I use OnChange Listener to make a toast when ever user change any button in list preferences.
But now I have 2 problems:
1-first time that user change an option toast is not shown
2-after that, when ever user change prefrences, the value of list is not updated, and is always set on second value.
this is my code:
public class PrefsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener{
private ListPreference myPreference;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences arg0, String key) {
ListPreference lp = (ListPreference) findPreference("blocktype");
lp.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// TODO Auto-generated method stub
Toast.makeText(PrefsActivity.this, "second", Toast.LENGTH_LONG).show();
return false;
}
});
}
}
What is
As no one answered my question I figured out, where is problem.
return false
should be changed to
return true
in order to update the preferences
In my application I would like to set a click listener on the individual preferencelist items in my preference activity, the problem is I can only find out how to set a click listener on the just the main listprefernce itself, is there a way I could set a key to the individual list items so when I set up an OnPreferenceClickListener I can execute some list item specific code?
make sure your preference class implements OnPreferenceClickListener and then override the onPreferenceClick then just check what preference key was pressed
#Override
public boolean onPreferenceClick(Preference preference) {
if (preference.getKey().equals("schedulestart")) {
showDialog(0);
} else if (preference.getKey().equals("schedulestop")) {
showDialog(1);
} else if (preference.getKey().equals("priority")) {
getPreferenceManager().getSharedPreferences().edit().putInt("unreadcount", 0).commit();
}
return true;
}
This question is relatively ancient, but I was looking to do a similar thing -- specifically get a hook in whenever any ListPreference item is clicked. Things like onSharedPreferenceChanged did not work for me because I need to do something even when the currently selected ListPreference is clicked. I'm not sure I understand the other answer here as solving the problem. My googling hasn't uncovered any other solutions.
I went along with extending ListPreference and overriding onDialogClosed(). The ListPreference source code for onDialogClosed is
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult && mClickedDialogEntryIndex >= 0 && mEntryValues != null) {
String value = mEntryValues[mClickedDialogEntryIndex].toString();
if (callChangeListener(value)) {
setValue(value);
}
}
}
I created a working interface to send the value of the selected list item in my new ListPreference and then overrode onDialogClosed:
public class MyListPreference extends ListPreference {
private ListItemClickListener mListItemClickListener;
...
public void setOnListItemClickListener(ListItemClickListener listener) {
mListItemClickListener = listener;
}
public interface ListItemClickListener {
public void onListItemClick(String value);
}
...
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult && getEntryValues() != null && mListItemClickListener != null) {
String value = getValue();
mListItemClickListener.onListItemClick(value);
}
}
Then, in your settings activity (or wherever you are using the new ListPreference), just hook it in:
#Override
protected void onResume() {
super.onResume();
MyListPreference listPref = (MyListPreference)
findPreference(getString(R.string.key_name));
listPref.setOnListItemClickListener(this);
}
...
public void onListItemClick(String value) {
// Do something
}
This works for my purposes.
I have an EditTextPreference. After the user has edited the preference and pressed ok I then want to check the value for formatting errors before committing.
public class Preferences_Default extends PreferenceActivity implements OnSharedPreferenceChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.prefs_default);
}
}
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
//This just calls a function to update the Pref Summary
Preference pref = findPreference(key);
initSummary(pref);
}
Where would I put the call to the function that checks the value and what is the code to re-commit the preference value if altered.
Friend, as you just specified, you have to check this in your code: you have to put it first line before it gets updated
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
//function to check
boolean b=check();
//This just calls a function to update the Pref Summary
if(b)
{
Preference pref = findPreference(key);
initSummary(pref);}
else{
//whatever you want to do show error
}
}