I'm build the Fun Facts app on the Android Development Track. I decided to take a exploratory detour and try to create a very basic introductory message to the user. I changed the factTextView text to "You can click the button below to see a new fact!" and changed the showFactButton text to "Try it out!"
From there, I changed the final line onClick object (is that an object?) to the following:
public void onClick(View view) {
String fact = mFactBook.getFact();
// Update the label with our dynamic fact
factLabel.setText(fact);
// Set button text to new fact prompt
showFactButton.setText("Show another fun fact.");
This seems to work fine. However, I feel like "updating" the button text to the same new string on every press isn't always the best practice, even if it is easy and readable. I tried to add a boolean that will check the text of the button, and update it only if it has not already been updated. This is what I've come up with so far:
View.OnClickListener listener = new View.OnClickListener() {
#Override
public String launchText = getResources().getString(R.string.start_text);
public String nextText = getResources().getString(R.string.next_text);
public String buttonText = (String) showFactButton.getText();
public boolean updateLaunchText() {
if (buttonText.equals(launchText)) {
buttonText.replaceAll(launchText, nextText);
return true;
}
else {
return true;
}
}
public void onClick(View view) {
String fact = mFactBook.getFact();
// Update the label with our dynamic fact
factLabel.setText(fact);
}
};
With the following added to strings.xml:
<string name="start_text">Try it out!</string>
<string name="next_text">Show another Fun Fact!</string>
No errors, but the button text stays on "Try it out!" I'm sure that all the extra objects are totally unnecessary compared to the first, working method for the scope of this app, but I'd still like to figure it out since I don't really have any idea what I'm doing with the boolean.
Questions: 1) What am I missing in the longer boolean approach? 2) What's the actual most efficient approach to accomplish this task?
Did you connect the listener to the button object?Without that connection no logic is applied to a button click.It goes like this:
buttonName.setOnClickListener(...)
You'd have to initialize the button object first though :)
Where r u call to method updateLaunchText() ?
you should change the objects to global object (not to create the into the listener):
private String launchText = getResources().getString(R.string.start_text);
private String nextText = getResources().getString(R.string.next_text);
private String buttonText = (String) showFactButton.getText();
and take the method updateLaunchText() out of the listener too.
and then into the onClick(View view) call to updateLaunchText() like this:
public void onClick(View view) {
updateLaunchText();
String fact = mFactBook.getFact();
// Update the label with our dynamic fact
factLabel.setText(fact);
}
I have a PreferenceScreen in which the user is capable, if system can't autodetect it, to enter the device's phone number. I'm still learning this part of Android but I managed to understand a bit of PreferenceScreens by examples provided by Android SDK itself and a few tutorials.
What I want is that the user can save the phone number only if null or valid, where by "valid" I mean running a generic validation logic (ie. an anonymous method that returns true or false, that can be reused in any possible situation*) or better, just to simplify things, ^(\+39)?3[0-9]{9}$
For now I have the following XML snip
<EditTextPreference
android:inputType="phone"
android:key="#string/preference_phoneNo"
android:selectAllOnFocus="true"
android:singleLine="true"
android:summary="#string/pref_phoneNumber_description"
android:title="#string/pref_phoneNumber" />
and following code by courtesy of Eclipse New Activity wizard:
private void setupSimplePreferencesScreen() {
if (!isSimplePreferences(this)) {
return;
}
addPreferencesFromResource(R.xml.pref_general);
bindPreferenceSummaryToValue(findPreference(getString(R.string.preference_phoneNo)));
}
addPreferenceFromResource is supposed to load the XML node and add the preference to the screen, while binPreferenceSummaryToValue is supposed to make description text change when preference is updated. Just for sake of completeness for those who don't like code courtesy of the IDE, the second method is provided by Eclipse who also provides a private class in the code file that is
/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.
*/
In the general case, what should I do to perform validation logic before the preference gets saved when I click OK on the preference editor? Where is the validation logic to be put in a PreferenceScreen?
*Aren't we all here to learn?
Android has a built in helper method for this.
String phoneNumber = ...;
boolean valid = PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber);
For a generic, re-usable method, here's the implementation of that method in PhoneNumberUtils, courtesy of AOSP (Apache licensed)
private static final Pattern GLOBAL_PHONE_NUMBER_PATTERN =
Pattern.compile("[\\+]?[0-9.-]+");
...
public static boolean isGlobalPhoneNumber(String phoneNumber) {
if (TextUtils.isEmpty(phoneNumber)) {
return false;
}
Matcher match = GLOBAL_PHONE_NUMBER_PATTERN.matcher(phoneNumber);
return match.matches();
}
Validation should occur within a Preference.OnPreferenceChangeListener , in the onPreferenceChange method. Simply return false if you don't want the value to be saved.
Example snippet:
private static Preference.OnPreferenceChangeListener myListener =
new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof PhoneNumberPreference) {
return isGlobalPhoneNumber(value);
}
}
...
As a note, since you're starting off with the Settings activity generated by the Eclipse wizard, this listener has already been built for you. You just need to edit it to include validation of the phone number (assuming that's what's being edited), and to return false if the number is invalid, so it won't be saved to preferences.
There is iOS US2FormValidator library for user input validation (see the picture below). I think that library is better than the default of just popping an alert when something doesn't validate.
I'm looking for how to do such things on Android. Are there some Android analogs of US2FormValidator?
The pop-up effect you have shown on your screenshot can be achieved using Android's built-in setError(String) method on EditText widgets.
Also, you can leverage the power of annotations using the Android Saripaar library that I've authored.
first add the library:
compile 'com.mobsandgeeks:android-saripaar:2.0.2'
The library is very simple to use. In your activity annotate the View references you would like to validate as in the following example.
#Order(1)
private EditText fieldEditText;
#Order(2)
#Checked(message = "You must agree to the terms.")
private CheckBox iAgreeCheckBox;
#Order(3)
#Length(min = 3, message = "Enter atleast 3 characters.")
#Pattern(regex = "[A-Za-z]+", message = "Should contain only alphabets")
private TextView regexTextView;
#Order(4)
#Password(min = 6, scheme = Password.Scheme.ALPHA_NUMERIC_MIXED_CASE_SYMBOLS)
private EditText passwordEditText;
#Order(5)
#ConfirmPassword
private EditText confirmPasswordEditText;
The order attribute specifies the order in which the fields have to be validated.
In your onCreate() method instantiate a new Validator object. and call validator.validate() inside any of your event listeners.
You'll receive callbacks on onSuccess and onFailure methods of the ValidationListener.
If you want to show a pop-up as show in the image above then do the following,
public void onValidationFailed(View failedView, Rule<?> failedRule) {
if (failedView instanceof Checkable) {
Toast.makeText(this, failedRule.getFailureMessage(), Toast.LENGTH_SHORT).show();
} else if (failedView instanceof TextView) {
TextView view = (TextView) failedView;
view.requestFocus();
view.setError(failedRule.getFailureMessage());
}
}
Android has extremely easy-to-use built-in validation mechanism which is great enough. See the following link:
http://blog.donnfelker.com/2011/11/23/android-validation-with-edittext/
I've just come across ValidationKomensky that you may find useful
https://github.com/inmite/android-validation-komensky
in my android application at some event in an activity I want to ask the user for a name (string). I know how to do this: call showDialog, create the dialog in the Activity.onCreateDialog method (I need to supply a string for the label) and handle the result in the onClick of the dialog. This works fine and to my satisfaction.
BUT this way I have three different places, where this simple task spreads throughout the code of my activity. I would much more prefer to keep this code together, to write some code like this:
string result;
if (showSimpleEditDialog(idForLabelString, result)==DIALOG_OK)
{
// do something with the result
}
or maybe with a class instance
SimpleEditDialog dlg = new SimpleEditDialog(idForLabelString);
if (dlg.showModal()==DIALOG_OK)
{
string result = dgl.getResult();
// do something with the result
}
(The "idForLabelString" would be some resource id for the label to use, DIALOG_OK would be some constant returned when the user clicks OK)
I know, I would have to write this methodes or this class. But for better readibility of my code I would do it. Any suggestions?
Thank you,
Gerhard
"BUT this way I have three different places, where this simple task spreads throughout the code"
So why don't you create a Method for this task? What you are talking about sounds like some sort of 'ActionListener' to me. This can be done in Java/Swing, but not in Android.
But, if you have three Dialogs, which all need to do the same when "YES" e.g. "NO" is pressed, you could define the 'DialogInterface.OnClickListener()' as a global inner-Class (or in a second class which extends the 'onClickListener') and then use it for all the Dialogs.
Now actually the problem with modal dialogs is mostly a problem with programm flow. You want to keep things together that belong together. You want to display a dialog that returns "ok" or "cancel" and additionaly e.g. a string that the user entered into one of the dialog widgets.
I do not want to write half of the code up to the line where I need the result of the dialog on one place and the rest of the code on another place namely the onClickListener of the dialog.
In some scenarios the first dialog might invoke a second dialog e.g. to specify a color which is not in the list of the first dialog's ListView.
Your code will be scattered all over the place (in each dialog's button onClickListener) and will be hard to read or to maintain.
Now after having written some unclear code like that I came up with the following solution which certainly respects the android design guides.
Instead of directly showing a dialog I create a Handler derived class which handles messages.
I send it a first message which creates and shows a dialog. It also forwards the handler to the dialog and the diaolg in it's onStop method sends another message to the handler, indicating the end of the dialog. There you can examine the dialogs properties, the contents of the edit fields or whether it was stopped with OK or CANCEL.
Now in the message handler all the logic of the task sits in different cases of the messages arg1 value.
Some cases might be skipped (e.g. the user selected a standard color and did not need a special color dialog).
The dialogs are independant of the scenario from which they are called and in their code only reflect their simple task (selecting from a list, some checkboxes etc.). They may be reused from other scenarios.
Following a kind of a template how to use this approach:
public class DoSomethingWithDialogs extends Handler
{
Context context; // from which it was called
final static int stepBegin = 0;
final static int stepNext = 1;
final static int stepSomethingElse = 2;
final static int stepLast = 3;
protected DoSomethingWithDialogs(Context context)
{
this.context = context;
}
public static void start(Context context)
{ // this is the main (only) entry point from outside
DoSomethingWithDialogs st = new DoSomethingWithDialogs(context);
st.sendMessage(st.obtainMessage(0, stepBegin, 0));
}
#Override
public void handleMessage(Message msg)
{
// step by step handling the task
switch (msg.arg1)
{
case stepBegin:
{
SomeDlg somedlg = new SomeDlg(context, this, stepNext);
// when the dialog closes, it sends a message to this with stepNext as arg1
somedlg.show();
}
break;
case stepNext:
{ // this message was send by the dialog when it finished
SomeDlg somedlg = (SomeDlg) msg.obj;
if (msg.arg2 == Dialog.BUTTON_NEGATIVE)
{
// has been canceled, nothing to do
} else
{
if (somedlg.someProperty)
{
} else
{
sendMessage(obtainMessage(0, stepSomethingElse, 0));
}
}
}
break;
case stepSomethingElse:
break;
}
}
}
I need to do form input validation on a series of EditTexts. I'm using OnFocusChangeListeners to trigger the validation after the user types into each one, but this doesn't behave as desired for the last EditText.
If I click on the "Done" button while typing into the final EditText then the InputMethod is disconnected, but technically focus is never lost on the EditText (and so validation never occurs).
What's the best solution?
Should I be monitoring when the InputMethod unbinds from each EditText rather than when focus changes? If so, how?
Why don't you use TextWatcher ?
Since you have a number of EditText boxes to be validated, I think the following shall suit you :
Your activity implements android.text.TextWatcher interface
You add TextChanged listeners to you EditText boxes
txt1.addTextChangedListener(this);
txt2.addTextChangedListener(this);
txt3.addTextChangedListener(this);
Of the overridden methods, you could use the afterTextChanged(Editable s) method as follows
#Override
public void afterTextChanged(Editable s) {
// validation code goes here
}
The Editable s doesn't really help to find which EditText box's text is being changed. But you could directly check the contents of the EditText boxes like
String txt1String = txt1.getText().toString();
// Validate txt1String
in the same method. I hope I'm clear and if I am, it helps! :)
EDIT: For a cleaner approach refer to Christopher Perry's answer below.
TextWatcher is a bit verbose for my taste, so I made something a bit easier to swallow:
public abstract class TextValidator implements TextWatcher {
private final TextView textView;
public TextValidator(TextView textView) {
this.textView = textView;
}
public abstract void validate(TextView textView, String text);
#Override
final public void afterTextChanged(Editable s) {
String text = textView.getText().toString();
validate(textView, text);
}
#Override
final public void beforeTextChanged(CharSequence s, int start, int count, int after) { /* Don't care */ }
#Override
final public void onTextChanged(CharSequence s, int start, int before, int count) { /* Don't care */ }
}
Just use it like this:
editText.addTextChangedListener(new TextValidator(editText) {
#Override public void validate(TextView textView, String text) {
/* Validation code here */
}
});
If you want nice validation popups and images when an error occurs you can use the setError method of the EditText class as I describe here
In order to reduce the verbosity of the validation logic I have authored a library for Android. It takes care of most of the day to day validations using Annotations and built-in rules. There are constraints such as #TextRule, #NumberRule, #Required, #Regex, #Email, #IpAddress, #Password, etc.,
You can add these annotations to your UI widget references and perform validations. It also allows you to perform validations asynchronously which is ideal for situations such as checking for unique username from a remote server.
There is a example on the project home page on how to use annotations. You can also read the associated blog post where I have written sample codes on how to write custom rules for validations.
Here is a simple example that depicts the usage of the library.
#Required(order = 1)
#Email(order = 2)
private EditText emailEditText;
#Password(order = 3)
#TextRule(order = 4, minLength = 6, message = "Enter at least 6 characters.")
private EditText passwordEditText;
#ConfirmPassword(order = 5)
private EditText confirmPasswordEditText;
#Checked(order = 6, message = "You must agree to the terms.")
private CheckBox iAgreeCheckBox;
The library is extendable, you can write your own rules by extending the Rule class.
Updated approach - TextInputLayout:
Google has recently launched design support library and there is one component called TextInputLayout and it supports showing an error via setErrorEnabled(boolean) and setError(CharSequence).
How to use it?
Step 1: Wrap your EditText with TextInputLayout:
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/layoutUserName">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="hint"
android:id="#+id/editText1" />
</android.support.design.widget.TextInputLayout>
Step 2: Validate input
// validating input on a button click
public void btnValidateInputClick(View view) {
final TextInputLayout layoutUserName = (TextInputLayout) findViewById(R.id.layoutUserName);
String strUsername = layoutLastName.getEditText().getText().toString();
if(!TextUtils.isEmpty(strLastName)) {
Snackbar.make(view, strUsername, Snackbar.LENGTH_SHORT).show();
layoutUserName.setErrorEnabled(false);
} else {
layoutUserName.setError("Input required");
layoutUserName.setErrorEnabled(true);
}
}
I have created an example over my Github repository, checkout the example if you wish to!
This was nice solution from here
InputFilter filter= new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
String checkMe = String.valueOf(source.charAt(i));
Pattern pattern = Pattern.compile("[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789_]*");
Matcher matcher = pattern.matcher(checkMe);
boolean valid = matcher.matches();
if(!valid){
Log.d("", "invalid");
return "";
}
}
return null;
}
};
edit.setFilters(new InputFilter[]{filter});
I wrote a class that extends EditText which supports natively some validation methods and is actually very flexible.
Current, as I write, natively supported through xml attributes validation methods are:
alpha
alpha numeric
numeric
generic regexp
string emptyness
You can check it out here
Hope you enjoy it :)
I find InputFilter to be more appropriate to validate text inputs on android.
Here's a simple example:
How do I use InputFilter to limit characters in an EditText in Android?
You could add a Toast to feedback the user about your restrictions.
Also check the android:inputType tag out.
I needed to do intra-field validation and not inter-field validation to test that my values were unsigned floating point values in one case and signed floating point values in another. Here's what seems to work for me:
<EditText
android:id="#+id/x"
android:background="#android:drawable/editbox_background"
android:gravity="right"
android:inputType="numberSigned|numberDecimal"
/>
Note, you must not have any spaces inside "numberSigned|numberDecimal". For example: "numberSigned | numberDecimal" won't work. I'm not sure why.
This looks really promising and just what the doc ordered for me:
EditText Validator
public void onClickNext(View v) {
FormEditText[] allFields = { etFirstname, etLastname, etAddress, etZipcode, etCity };
boolean allValid = true;
for (FormEditText field: allFields) {
allValid = field.testValidity() && allValid;
}
if (allValid) {
// YAY
} else {
// EditText are going to appear with an exclamation mark and an explicative message.
}
}
custom validators plus these built in:
regexp: for custom regexp
numeric: for an only numeric field
alpha: for an alpha only field
alphaNumeric: guess what?
personName: checks if the entered text is a person first or last name.
personFullName: checks if the entered value is a complete full name.
email: checks that the field is a valid email
creditCard: checks that the field contains a valid credit card using Luhn Algorithm
phone: checks that the field contains a valid phone number
domainName: checks that field contains a valid domain name ( always passes the test in API Level < 8 )
ipAddress: checks that the field contains a valid ip address
webUrl: checks that the field contains a valid url ( always passes the test in API Level < 8 )
date: checks that the field is a valid date/datetime format ( if customFormat is set, checks with customFormat )
nocheck: It does not check anything except the emptyness of the field.
In main.xml file
You can put the following attrubute to validate only alphabatics character can accept in edittext.
Do this :
android:entries="abcdefghijklmnopqrstuvwxyz"
You can get desired behavior by listening when user hit "Done" button on keyboard, also checkout other tips about working with EditText in my post "Android form validation - the right way"
Sample code:
mTextView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
validateAndSubmit();
return true;
}
return false;
}});
for email and password validation try
if (isValidEmail(et_regemail.getText().toString())&&etpass1.getText().toString().length()>7){
if (validatePassword(etpass1.getText().toString())) {
Toast.makeText(getApplicationContext(),"Go Ahead".....
}
else{
Toast.makeText(getApplicationContext(),"InvalidPassword".....
}
}else{
Toast.makeText(getApplicationContext(),"Invalid Email".....
}
public boolean validatePassword(final String password){
Pattern pattern;
Matcher matcher;
final String PASSWORD_PATTERN = "^(?=.*[0-9])(?=.*[A-Z])(?=.*
[##$%^&+=!])(?=\\S+$).{4,}$";
pattern = Pattern.compile(PASSWORD_PATTERN);
matcher = pattern.matcher(password);
return matcher.matches();
}
public final static boolean isValidEmail(CharSequence target) {
if (target == null)
return false;
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
I have created this library for android where you can validate a material design EditText inside and EditTextLayout easily like this:
compile 'com.github.TeleClinic:SmartEditText:0.1.0'
then you can use it like this:
<com.teleclinic.kabdo.smartmaterialedittext.CustomViews.SmartEditText
android:id="#+id/passwordSmartEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:setLabel="Password"
app:setMandatoryErrorMsg="Mandatory field"
app:setPasswordField="true"
app:setRegexErrorMsg="Weak password"
app:setRegexType="MEDIUM_PASSWORD_VALIDATION" />
<com.teleclinic.kabdo.smartmaterialedittext.CustomViews.SmartEditText
android:id="#+id/ageSmartEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:setLabel="Age"
app:setMandatoryErrorMsg="Mandatory field"
app:setRegexErrorMsg="Is that really your age :D?"
app:setRegexString=".*\\d.*" />
Then you can check if it is valid like this:
ageSmartEditText.check()
For more examples and customization check the repository
https://github.com/TeleClinic/SmartEditText