I need to check the user input in the preferences if they want to save a new value. I believe the code is correct... because if I'm change the values slowly there's no problem at all. If I change too quick the app is crashing.
i'm using commit() for editing the preferences. Is this a too slow methode?
What I'm trying?: If a user gave an empty string, I give an alert dialog and intern I change the pref back to the old value. Here is the code:
public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {
//save settings
static String SMStext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
//-- First get SMStext and save in Strings
SMStext = sp.getString("SMSText", "0");
//SharedPreferences.Editor prefEditor = sp.edit();
sp.registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
String smstriggerworderror = "String cannot be empty";
if (key.equals("SMSText")) {
if sp.getString("SMSText", "0").equals(""){
SharedPreferences.Editor prefEditor = sp.edit();
prefEditor.putString("SMSText", SMStext);
prefEditor.commit();
//write current value back to value and refresh interface
SMStext = sp.getString("SMSText", "0");
//Show alert dialog
showdialog(smstriggerworderror);
//finish();
}
//write current value back to value
SMStext = sp.getString("SMSText", "0");
}
private void showdialog(String message) {
//create alertbox
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setMessage(message);
alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
// Click listener on the neutral button or alert box
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
});
// show the alert box
alertbox.show();
}