how to show an error for EditTextPreference - android

I am trying to show the user an error when they enter a value for an EditTextPreference incorrectly.
Currently I have a onPreferenceChangeListener which returns true or false:
editTextPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (newValue.toString().length() < 1 || Integer.parseInt(newValue.toString()) < 1) {
return false;
} else {
return true;
}
}
});
I found this question Design Android EditText to show error message as described by google, but it is for a EditText not an EditTextPreference. Now I am trying to find a similar solution that I can use for EditTextPreference.
Thank you for your help!

Related

Android: onPreferenceChange with validation

Quick overview:
I have built validation that works with onPreferenceChanged on a sample project designed just to test settings and how they're saved and such. The functionality is all there and works as I desire it to. I was hoping to be able to move this functionality over into the default generated SettingsActivity class since it appears to provide solid functionality and much needed headers for the expansion of the program.
The code itself I would like to implement is what's been provided below. Very briefly I have a check which decides if a specific verification or not needs to be implemented and if so it attaches the specific one, otherwise it attaches a generic one. I believe this to be a hacky method and would like an alternative if possible.
// Type of verification checking to attach
public void attachOnPreferenceChangedListener(Preference dsp_pref) {
if (dsp_pref.getKey().equals("et_targetPref")) {
attachTargetVerifier(dsp_pref);
} else { // Any non verifier specific is given a generic listen with summary updater
attachGenericVerifier(dsp_pref);
}
}
private void attachGenericVerifier(Preference dsp_pref) {
dsp_pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
updatePrefSummary(preference);
return true;
}
});
}
private void attachTargetVerifier(Preference dsp_pref) {
dsp_pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
Pattern dsl_pattern = Pattern.compile(URL_REGEX,Pattern.CASE_INSENSITIVE);
Matcher dsl_matcher = dsl_pattern.matcher(newValue.toString());
if (!dsl_matcher.matches()) {
Toast.makeText(getActivity(), "Invalid URL. Example: http://example.com/target", Toast.LENGTH_LONG).show();
} else if (dsl_matcher.group(1).toLowerCase().endsWith("/target")) {
Toast.makeText(getActivity(), "Preference Saved", Toast.LENGTH_LONG).show();
updatePrefSummary(preference);
return true;
} else if(dsl_matcher.group(2) == null) {
Toast.makeText(getActivity(), "URL must start with 'http://'", Toast.LENGTH_LONG).show();
} else {
}
return false;
}
});
}
What the default SettingsActivity provides is just a simple and straightforward OnPreferenceChange override, which probably means validation checking needs to be integrated here unless a more elegant method exists, in which case I'm all ears:
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else if (preference instanceof RingtonePreference) {
// For ringtone preferences, look up the correct display value
// using RingtoneManager.
if (TextUtils.isEmpty(stringValue)) {
// Empty values correspond to 'silent' (no ringtone).
preference.setSummary(R.string.pref_ringtone_silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));
if (ringtone == null) {
// Clear the summary if there was a lookup error.
preference.setSummary(null);
} else {
// Set the summary to reflect the new ringtone display
// name.
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
};
Appreciate any advice on how this can be done without it becoming unmanageable
The solution, for those interested, while not complete and 100% is to place the small validation block at the top, if validation fails a return false is carried out:
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
///////////////////////////////////////////////////////////////////
// Preference Validation Section
///////////////////////////////////////////////////////////////////
// URL Check: http://whatev.er/targetstore
if (preference.getKey().equals("connect_url")) {
Pattern dsl_pattern = Pattern.compile(URL_REGEX,Pattern.CASE_INSENSITIVE);
Matcher dsl_matcher = dsl_pattern.matcher(stringValue);
if (dsl_matcher.matches() && // Match!
dsl_matcher.group(1).toLowerCase().endsWith("/targetstore")) { // Confirmed validity
Toast.makeText(dsl_context, "Preference Saved", Toast.LENGTH_LONG).show();
} else { // No match - don't save data.
Toast.makeText(dsl_context, "Invalid URL. Example: http://example.com/targetstore", Toast.LENGTH_LONG).show();
return false; // Stops result from saving
}
}
if (preference instanceof ListPreference) {
//List Pref setSummary
} else if (preference instanceof RingtonePreference) {
//Ringtone Pref setSummary
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
};
There is still an issue whenever the settings are loaded, a "Preference Saved" prompt will be shown. Some check verifying whether data is being read and not set might help solve this, I have no knowledge of such a check however.

Check textfield is empty in Android Studio

I am trying to check whether my textfield is empty for validation purpose but i am getting an error message cannot resolve method isEmpty
This is my partial coding:
private void addMovie(){
DatabaseHandler databaseHandler = new DatabaseHandler(getApplicationContext());
if(getIntent().getExtras()== null){
databaseHandler.insertRow(
mvidEditText.getText().toString(),
mvtitleEditText.getText().toString(),
mvtypeEditText.getText().toString(),
mvstoryEditText.getText().toString(),
mvratingEditText.getText().toString(),
mvlanguageEditText.getText().toString(),
Integer.parseInt(mvruntimeEditText.getText().toString()));
if (mvidEditText.isEmpty() || mvtitleEditText.matc) {
Toast.makeText(this, "You did not enter a username", Toast.LENGTH_SHORT).show();
return;
}
}else {
databaseHandler.updateRow(rowID,
mvidEditText.getText().toString(),
mvtitleEditText.getText().toString(),
mvtypeEditText.getText().toString(),
mvstoryEditText.getText().toString(),
mvratingEditText.getText().toString(),
mvlanguageEditText.getText().toString(),
Integer.parseInt(mvruntimeEditText.getText().toString()));
}
}
Are there any ways to do this? I did some research from stack overflow too.Thank you.
Now in new version getText() is not working directly so use only text
like this
if (enter_name.text.toString().isEmpty()) {
}
As far as my knowledge goes, there is no method isEmpty() in EditText class. you should do like this-
if(!TextUtils.isEmpty(editTextRef.getText().toString())){
///.... your remaining code if the edittext is not empty
}
if(mvidEditText.getText().length() == 0){}
you can try following for checking empty value for edittext
mvidEditText.getText().toString().isEmpty();
where isEmpty returns true if length of this string is 0.
if(mvidEditText.getText().toString().equals("")){print message here}
to check Edittext is empty
if(myeditText.getText().toString().trim().length() == 0)
Or use below function
private boolean isEmpty(EditText editText) {
return editText.getText().toString().trim().length() == 0;
}

Android adding OnPreferenceChangeListener to MultiSelectListPreference(MSLP) stops MSLP from working

My minimum SDK is Android 4.0. When I try to add an OnPreferenceChangeListener to MultiSelectListPreference, it stops MSLP from storing the changed values. It works fine without the listener, and even with my code commented out it seems to fail.
private void init () {
MultiSelectListPreference multiSelectListPref = (MultiSelectListPreference) findPreference("repeat_days");
if (multiSelectListPref != null) {
/* Works fine if this is commented out
multiSelectListPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
//formatSummary((MultiSelectListPreference) preference, newValue);
return false;
}
});*/
}
}
I need to know when the user changes the information. I have seen this response
MultiSelectListPreference not storing values? but I can not seem to get even that to work.
Any help is appreciated, Thanks in advance!
You can view google's code here (https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/preference/MultiSelectListPreference.java). The pertinent method is:
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult && mPreferenceChanged) {
final Set<String> values = mNewValues;
if (callChangeListener(values)) {
setValues(values);
}
}
mPreferenceChanged = false;
}
So when you return false in your onPreferenceChange() method, you are explicitly telling it not to save your updated values. Return true and this should do what you expect.
The other SO posts suggest there have been various bugs in this preference implementation at various SDK levels. YMMV.

Random boolean generator for android

I am trying to create a random (50/50) chance of a case A or case B happen in android and I need it to be as simple and as resource efficient as possible. I've looked through stackoverflow but all I find for random boolean is in C++?
Would appreciate if someone could give me a suggestion as to how to do this, whether with boolean or with strings/integers (since I was told that booleans is a primitive).
I tried the following
public static boolean getRandomBoolean() {
return Math.random() < 0.5; }
boolean atrg = getRandomBoolean();
if (atrg = true)
{ Toast.makeText(cxt, "TRUE", Toast.LENGTH_SHORT).show(); }
else if (atrg = false)
{ Toast.makeText(cxt, "FALSE", Toast.LENGTH_SHORT).show(); }
But in nearly every case, I tested (>20x), its TRUE?. This is likely a stupid question but is getRandomBoolean a boolean or an int/double? Sorry, I'm very new to android, as you probably guessed.
Your random generator is fine, but your toast displaying the result is not.
The problem is in the if-statement where you use a single equals sign (=) which is an assignment. The result of this assignment will be true and thus it will never show the "FALSE" toast.
Try this instead.
boolean atrg = getRandomBoolean();
if (atrg) {
Toast.makeText(cxt, "TRUE", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(cxt, "FALSE", Toast.LENGTH_SHORT).show();
}
This is not how you check boolean in if. = is the assignment operator and == is used for comparison. You should check like:
if(atrg == true)
or in case of boolean it is simply:
if(atrg)
Your statement:
if(atrg = true)
assigns atrg with true and you never get a false case.
Just use Math.random(), it will return a value between 0 and 1.. Example below:
public static boolean getRandomBoolean() {
return Math.random() < 0.5;
}
public static void main(String[] args) {
System.out.println(getRandomBoolean());
}

How to setOnClickListener() to OK button of an EditTextPreference Dialog? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to call the ok button in the EditTextPreference
I want to validate the Inputs (enter 6 digits) of an EditTextPreference dialog box.
This is how my (relevant) preferences.xml snippet looks like :
<!--EditTextPreference-->
<com.app.preferences.UpdatePincodePreference
android:key="PIN_CODE_PREFERENCE"
android:title="#string/pincode_preference_title"
android:summary="#string/pincode_preference_summary"
android:dialogTitle="#string/pincode_preference_dialog_title"
android:dialogMessage="#string/pincode_preference_dialog_message"
android:inputType="number"
/>
How do I test that the user has not entered less or more than 6 digits in the EditText of the preference dialog?
Basically I need to set an onClickListener() on the OK button, but how to I get a hold of the OK button which I did not define. Its the default view of an EditTextPreference, and so is the Cancel button.
The question is exactly the same as "how to call the ok button in the EditTextPreference" but the links provided in the accepted solution are broken now.
The author of the solution has moved his project from Google Code to GitHub. You can find the new project at https://github.com/Knickedi/android-toolbox and the links to the two files he was referring to validating DialogPreference and validating EditTextPreference
This could be achieved using setOnPreferenceChangeListener()
public UpdatePasswordPreference(Context context, AttributeSet attrs) {
this.setOnPreferenceChangeListener(new OnPreferenceChangeListener()
{
#Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
MobicopLogger.d("Preference input changed");
try
{
if(newValue.toString().length() != 6)
return false;
else
return true;
}
catch(Exception e)
{
return false;
}
}
});
}
create a custom layout and apply it to the preference by the following override method :
#Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
super.onPrepareDialogBuilder(builder); //To change body of overridden methods use File | Settings | File Templates.
builder.setView(LayoutInflater.from(ctx).inflate(R.layout.custome_preference_layout,null));
}

Categories

Resources