Hot questions for Using Android EditText in validation

Question:

I am working on a project where the user is allowed to type only password with letters, alphabets and special characters like (@.#$%^&_-&*) alone in a edittext. I tried various methods like. **Note: space is strictly restricted

Method 1:

setting digits in layout as follows

android:digits="0,1,2,3,4,5,6,7,8,9,*@#$%_-\^.&<qwertzuiopasdfghjklyxcvbnmABCDEFGHIJKLMNOPQRSTUVWXYZ"

This method is working fine but i could able to type brackets'(', semicolon ';' and i could not type slash '\' (which i have added in the digits tag)

Method 2:

By trying regex with following method

public static boolean limitPasswordCharacters(String about){
        // UserName Validation Pattern String
        final Pattern USER_NAME_PATTERN = Pattern.compile("^[a-zA-Z0-9@.#$%^&*_&\\]+$");
        if(USER_NAME_PATTERN.matcher(about).matches()){
            return true;            
        }
        return false;
    }

But unfortunately gettting exception as

11-17 16:18:11.155: E/AndroidRuntime(15877): java.util.regex.PatternSyntaxException: Missing closing bracket in character class near index 22:
11-17 16:18:11.155: E/AndroidRuntime(15877): [a-zA-Z0-9@.#$%^&*_&\]

Answer:

Change your pattern like below,

final Pattern USER_NAME_PATTERN = Pattern.compile("^[a-zA-Z0-9@.#$%^&*_&\\\\]+$");

In java regex, to mean a backslash, you need to escape it three times. Java consider this \\] as a lietral ] bracket.

Example:

String digits="0,1,2,3,4,5,6,7,8,9,*@#$%_-\\^.&<qwertzuiopasdfghjklyxcvbnmABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println(digits.matches("^[-a-zA-Z0-9@.#$%^&*_&,<\\\\]+$")); //true

Question:

I am using the fololowing code to validate the email input

  private boolean validateEmail(String email) {
        String emailPattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
        Pattern pattern = Pattern.compile(emailPattern);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }

I execute this on onTextChanged. The code is below (I am using ButterKnife)

@OnTextChanged(R.id.et_email)
    public void checkCorrectEmail() {
        if (!validateEmail(mEditTextEmail.getText().toString().trim())) {
            isValidated = false;
            mEditTextEmail.setError("Please enter email address");
            mEditTextEmail.requestFocus();
        } else {
            isValidated = true;
        }
    }

The issue is that it is not intelligent enough. For an example, if I type myemail@gmail.com it still show the error message. However if I type myemail@gmail.com then a space and clicked delete the space then everything is fine, error gone.

Formerly this validation was on onClick of a button. What have I done wrong here?


Answer:

    @OnTextChanged(R.id.et_email)
        public void checkCorrectEmail () {
            if (!validateEmail(mEditTextEmail.getText().toString().trim())) {
                isValidated = false;
                mEditTextEmail.setError("Please enter email address");
                mEditTextEmail.requestFocus();
            } else {
                isValidated = true;
                mEditTextEmail.setError(null);
            }
}

100% working

Question:

I am trying to validate some edittext. I Made 7 edittexts. Phone number ,First name , Last name , Pickup Address, Postal Code, Pickup time, Number of products. As u can see i made 7 edittexts and I want to validate them so that when i press the button to go to next page it does all the database posting and getting on that button. I've already made a method (public void addInfo) and now i am adding the validations on the View.OnClick implemented methods. Here is my Code i wrote for validations.

public void onClick(View v) {

        if (v == nextbuttonjava) {


            if(phnumberjava.getText().toString().length() < 10)
            {

                phnumberjava.setError("Invalid Phone Number");
            }
            if(firstnamejava.getText().toString().length() == 0)
            {
                firstnamejava.setError("Whats your first name?");
            }
            if(lastnamejava.getText().toString().length() == 0)
            {
                lastnamejava.setError("Whats your last name?");
            }
            if(pickupaddressjava.getText().toString().length() == 0)
            {
                pickupaddressjava.setError("Enter your address");
            }
            if(postalcodejava.getText().toString().length() < 6)
            {
                postalcodejava.setError("Invalid postal code");
            }
            if(pickuptimejava.getText().toString().length() == 0)
            {
                pickuptimejava.setError("Enter pickuptime");
            }
            if(numberstuffjava.getText().toString().length() == 0) {


                numberstuffjava.setError("Enter number of clothes");
            }
            else
            {
                addInfo();
                Intent nextpageintent = new Intent(Afterfullscreen.this, Extrainformation.class);
                startActivity(nextpageintent);
            }



        }
    }

I Want that every If statement should be true to make the else work so the intent works and i go to the other activity. But its not the scene here. Only the phone number works good(If i enter the phone number below 10 digits it shows the error and it doesn't run else part). My main concern is that I Have 7 edittexts and Even if one If statement goes true then the else shouldn't be running and i shouldn't go to next intent with posting incomplete data on my database.I Want that even if any of the edittexts if statement goes wrong i should get an error (eg, numberstuffjava.setError("Input Something");.

How to resolve the issue?


Answer:

Try something like this:

public void onClick(View v) {

    if (v == nextbuttonjava) {
        boolean error = false;

        if(phnumberjava.getText().toString().length() < 10)
        {
            error = true;
            phnumberjava.setError("Invalid Phone Number");
        }
        if(firstnamejava.getText().toString().isEmpty())
        {
            error = true;
            firstnamejava.setError("Whats your first name?");
        }
        if(lastnamejava.getText().toString().isEmpty())
        {
            error = true;
            lastnamejava.setError("Whats your last name?");
        }
        if(pickupaddressjava.getText().toString().isEmpty())
        {
            error = true;
            pickupaddressjava.setError("Enter your address");
        }
        if(postalcodejava.getText().toString().length() < 6)
        {
            error = true;
            postalcodejava.setError("Invalid postal code");
        }
        if(pickuptimejava.getText().toString().isEmpty())
        {
            error = true;
            pickuptimejava.setError("Enter pickuptime");
        }
        if(numberstuffjava.getText().toString().isEmpty()) 
        {
            error = true;
            numberstuffjava.setError("Enter number of clothes");
        }
        if(!error)
        {
            addInfo();
            Intent nextpageintent = new Intent(Afterfullscreen.this, Extrainformation.class);
            startActivity(nextpageintent);
        } else {
             //manage error case here
        }
    }
}

another option could be this:

if (v == nextbuttonjava) {

    if(phnumberjava.getText().toString().length() < 10)
    {
        phnumberjava.setError("Invalid Phone Number");
    }
    else if(firstnamejava.getText().toString().isEmpty())
    {
        firstnamejava.setError("Whats your first name?");
    }
    else if(lastnamejava.getText().toString().isEmpty())
    {
        lastnamejava.setError("Whats your last name?");
    }
    else if(pickupaddressjava.getText().toString().isEmpty())
    {
        pickupaddressjava.setError("Enter your address");
    }
    else if(postalcodejava.getText().toString().length() < 6)
    {
        postalcodejava.setError("Invalid postal code");
    }
    else if(pickuptimejava.getText().toString().isEmpty())
    {
        pickuptimejava.setError("Enter pickuptime");
    }
    else if(numberstuffjava.getText().toString().isEmpty()) 
    {
        numberstuffjava.setError("Enter number of clothes");
    }
    else 
    {
        addInfo();
        Intent nextpageintent = new Intent(Afterfullscreen.this, Extrainformation.class);
        startActivity(nextpageintent);
    }
    else
    {
         //manage error case here
    }
}

In this way you check any case with the else if. I prefer the first solution because it's more "flexible".

Hope this helps!

Question:

I have one EditText which is unEditable for user. I'm taking value to EditText by Calendar object. So when user submit form without selecting time it will show message to select time.

etTime.setError("Select Time");

Now user selects date from Calendar.

etTime.setText(functionWhichReturnsSelectedTime());

I'm talking about that Red Alert Sign which appears on side of EditText!!!

But the error message doesn't get away. The listener only listens to textChanged() of EditText and checks is EditText is empty or not? But I'm not providing user to access editability of EditText. So error is not getting away.

So how can I manually do that?


Answer:

If you want to remove the error indicator on your edit text, you must call:

etTime.setError(null);

Also, it would be a good idea, to override afterTextChanged() method, and you can perform validation, before removing the error.

Question:

In my application I want use EditText and for this I should set limited for this EditText. In my EditText JUST support alphabet (a-z, A-Z) and for this I wrote below code:

registerUsernameEdtTxt.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        registerUsernameEdtTxt.setFilters(new InputFilter[]{new InputFilter() {
            public CharSequence filter(CharSequence src, int start,
                                       int end, Spanned dst, int dstart, int dend) {
                if (src != null && src.length() > 0 && dstart == 0) {
                    if (src.toString().matches("[a-zA-Z ].*")) {
                        registerUsernameInptLay.setErrorEnabled(false);
                        return src;
                    }
                } else {
                    registerUsernameInptLay.setError(context.getResources().getString(R.string.insertJustEnglish));
                }
                return "";
            }
        }});
    }

XML code:

<android.support.design.widget.TextInputLayout
                                android:id="@+id/registerUsernameInptLay"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_below="@+id/registerUserNameErrTxt"
                                app:counterEnabled="true"
                                app:counterMaxLength="20">

                                <EditText
                                    android:id="@+id/registerUsernameEdtTxt"
                                    android:layout_width="match_parent"
                                    android:layout_height="wrap_content"
                                    android:fontFamily="sans-serif"
                                    android:hint="@string/registerUsername"
                                    android:inputType="text"
                                    android:textColor="@color/darkBlueGrey"
                                    android:textSize="@dimen/font16" />
                            </android.support.design.widget.TextInputLayout>

But when write Characters show me this error:

   <string name="insertJustEnglish">Username can only start with alphabet characters.</string>

How can I fix it?


Answer:

Write this in your EditText tag

android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

Question:

I want to create an OTP code for my application, so how to create an country code for phone number validation. If you have solved problem like this, please share to me. thanks


Answer:

Create a xml file having name country_codes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string-array name="country_code">
        <item>+93,</item>
        <item>+355,</item>
        <item>+213,</item>
        <item>+684,</item>
        <item>+376,</item>
        <item>+244,</item>
        <item>+1&#8211;264,</item>
        <item>+672,</item>
        <item>+1&#8211;268,</item>
        <item>+54,</item>
        <item>+374,</item>
        <item>+297,</item>
        <item>+61,</item>
        <item>+43,</item>
        <item>+994,</item>
        <item>+1&#8211;242,</item>
        <item>+973,</item>
        <item>+ 880,</item>
        <item>+1&#8211;246,</item>
        <item>+375,</item>
        <item>+32,</item>
        <item>+501,</item>
        <item>+229,</item>
        <item>+1&#8211;441,</item>
        <item>+975,</item>
        <item>+591,</item>
        <item>+387,</item>
        <item>+267,</item>
        <item>+55,</item>
        <item>+673,</item>
        <item>+359,</item>
        <item>+226,</item>
        <item>+257,</item>
        <item>+855,</item>
        <item>+237,</item>
        <item>+1,</item>
        <item>+238,</item>
        <item>+1&#8211;345,</item>
        <item>+236,</item>
        <item>+235,</item>
        <item>+56,</item>
        <item>+86,</item>
        <item>+61,</item>
        <item>+61,</item>
        <item>+57,</item>
        <item>+269,</item>
        <item>+242,</item>
        <item>+243,</item>
        <item>+682,</item>
        <item>+506,</item>
        <item>+385,</item>
        <item>+53,</item>
        <item>+357,</item>
        <item>+420,</item>
        <item>+45,</item>
        <item>+253,</item>
        <item>+1&#8211;767,</item>
        <item>+809,</item>
        <item>+593,</item>
        <item>+20,</item>
        <item>+503,</item>
        <item>+240,</item>
        <item>+291,</item>
        <item>+372,</item>
        <item>+251,</item>
        <item>+500,</item>
        <item>+298,</item>
        <item>+679,</item>
        <item>+358,</item>
        <item>+33,</item>
        <item>+594,</item>
        <item>+241,</item>
        <item>+220,</item>
        <item>+995,</item>
        <item>+49,</item>
        <item>+233,</item>
        <item>+350,</item>
        <item>+44,</item>
        <item>+30,</item>
        <item>+299,</item>
        <item>+1&#8211;473,</item>
        <item>+590,</item>
        <item>+1&#8211;671,</item>
        <item>+502,</item>
        <item>+224,</item>
        <item>+245,</item>
        <item>+592,</item>
        <item>+509,</item>
        <item>+504,</item>
        <item>+852,</item>
        <item>+36,</item>
        <item>+354,</item>
        <item>+91,</item>
        <item>+62,</item>
        <item>+98,</item>
        <item>+964,</item>
        <item>+353,</item>
        <item>+972,</item>
        <item>+39,</item>
        <item>+225,</item>
        <item>+1&#8211;876,</item>
        <item>+81,</item>
        <item>+962,</item>
        <item>+7,</item>
        <item>+254,</item>
        <item>+686,</item>
        <item>+850,</item>
        <item>+82,</item>
        <item>+965,</item>
        <item>+996,</item>
        <item>+856,</item>
        <item>+371,</item>
        <item>+961,</item>
        <item>+266,</item>
        <item>+231,</item>
        <item>+218,</item>
        <item>+423,</item>
        <item>+370,</item>
        <item>+352,</item>
        >
        <item>+853,</item>
        <item>+389,</item>
        <item>+261,</item>
        <item>+265,</item>
        <item>+60,</item>
        <item>+960,</item>
        <item>+223,</item>
        <item>+356,</item>
        <item>+692,</item>
        <item>+596,</item>
        <item>+222,</item>
        <item>+230,</item>
        <item>+269,</item>
        <item>+52,</item>
        <item>+691,</item>
        <item>+373,</item>
        <item>+377,</item>
        <item>+976,</item>
        <item>+382,</item>
        <item>+1&#8211;664,</item>
        <item>+212,</item>
        <item>+258,</item>
        <item>+95,</item>
        <item>+264,</item>
        <item>+674,</item>
        <item>+977,</item>
        <item>+31,</item>
        <item>+599,</item>
        <item>+687,</item>
        <item>+64,</item>
        <item>+505,</item>
        <item>+227,</item>
        <item>+234,</item>
        <item>+683,</item>
        <item>+672,</item>
        <item>+670,</item>
        <item>+47,</item>
        <item>+968,</item>
        <item>+92,</item>
        <item>+680,</item>
        <item>+507,</item>
        <item>+675,</item>
        <item>+595,</item>
        <item>+51,</item>
        <item>+63,</item>
        <item>+48,</item>
        <item>+689,</item>
        <item>+351,</item>
        <item>+1&#8211;787,</item>
        <item>+974,</item>
        <item>+262,</item>
        <item>+40,</item>
        <item>+7,</item>
        <item>+250,</item>
        <item>+290,</item>
        <item>+1&#8211;869,</item>
        <item>+1&#8211;758,</item>
        <item>+508,</item>
        <item>+1&#8211;784,</item>
        <item>+684,</item>
        <item>+378,</item>
        <item>+239,</item>
        <item>+966,</item>
        <item>+221,</item>
        <item>+381,</item>
        <item>+248,</item>
        <item>+232,</item>
        <item>+65,</item>
        <item>+421,</item>
        <item>+386,</item>
        <item>+677,</item>
        <item>+252,</item>
        <item>+27,</item>
        <item>+34,</item>
        <item>+94,</item>
        <item>+249,</item>
        <item>+597,</item>
        <item>+268,</item>
        <item>+46,</item>
        <item>+41,</item>
        <item>+963,</item>
        <item>+886,</item>
        <item>+992,</item>
        <item>+255,</item>
        <item>+66,</item>
        <item>+228,</item>
        <item>+690,</item>
        <item>+676,</item>
        <item>+1&#8211;868,</item>
        <item>+216,</item>
        <item>+90,</item>
        <item>+993,</item>
        <item>+1&#8211;649,</item>
        <item>+688,</item>
        <item>+44,</item>
        <item>+1,</item>
        <item>+256,</item>
        <item>+380,</item>
        <item>+971,</item>
        <item>+598,</item>
        <item>+998,</item>
        <item>+678,</item>
        <item>+39,</item>
        <item>+58,</item>
        <item>+84,</item>
        <item>+1&#8211;284,</item>
        <item>+1&#8211;340,</item>
        <item>+681,</item>
        <item>+967,</item>
        <item>+260,</item>
        <item>+263,</item>


    </string-array>
    <string-array name="country_name">
        <item>Afghanistan</item>
        <item>Albania</item>
        <item>Algeria</item>
        <item>American Samoa</item>
        <item>Andorra</item>
        <item>Angola</item>
        <item>Anguilla</item>
        <item>Antarctica</item>
        <item> Antigua and Barbuda</item>
        <item>Argentina</item>
        <item>Armenia</item>
        <item>Aruba</item>
        <item>Australia</item>
        <item>Austria</item>
        <item>Azerbaijan</item>
        <item>Bahamas</item>
        <item>Bahrain</item>
        <item>Bangladesh</item>
        <item>Barbados</item>
        <item>Belarus</item>
        <item>Belgium</item>
        <item>Belize</item>
        <item>Benin</item>
        <item>Bermuda</item>
        <item>Bhutan</item>
        <item>Bolivia</item>
        <item>Bosnia-Herzegovina</item>
        <item>Botswana</item>
        <item>Brazil</item>
        <item>Brunei Darussalam</item>
        <item>Bulgaria</item>
        <item>Burkina Faso</item>
        <item>Burundi</item>
        <item>Cambodia</item>
        <item>Cameroon</item>
        <item>Canada</item>
        <item>Cape Verde </item>
        <item>Cayman Islands</item>
        <item>Central African Republic</item>
        <item>Chad </item>
        <item>Chile </item>
        <item>China </item>
        <item>Christmas Island</item>
        <item>Cocos (Keeling) Islands</item>
        <item>Colombia </item>
        <item>Comoros </item>
        <item>Congo </item>
        <item>Congo, Dem. Republic </item>
        <item>Cook Islands</item>
        <item>Costa Rica </item>
        <item>Croatia</item>
        <item>Cuba </item>
        <item>Cyprus</item>
        <item>Czech </item>
        <item>Denmark </item>
        <item>Djibouti</item>
        <item>Dominica </item>
        <item>Dominican</item>
        <item>Ecuador </item>
        <item>Egypt </item>
        <item>El Salvador</item>
        <item>Equatorial</item>
        <item>Eritrea </item>
        <item>Estonia </item>
        <item>Ethiopia </item>
        <item>Falkland Islands (Malvinas)</item>
        <item>Faroe Islands</item>
        <item>Fiji</item>
        <item>Finland </item>
        <item>France </item>
        <item>French Guiana</item>
        <item>Gabon</item>
        <item>Gambia </item>
        <item>Georgia </item>
        <item>Germany </item>
        <item>Ghana </item>
        <item>Gibraltar </item>
        <item>Great Britain </item>
        <item>Greece </item>
        <item>Greenland</item>
        <item>Grenada </item>
        <item>Guadeloupe (French) </item>
        <item>Guam (USA)</item>
        <item>Guatemala </item>
        <item>Guinea </item>
        <item>Guinea Bissau </item>
        <item>Guyana </item>
        <item>Haiti </item>
        <item>Honduras </item>
        <item>Hong Kong </item>
        <item>Hungary </item>
        <item>Iceland </item>
        <item>India </item>
        <item>Indonesia </item>
        <item>Iran </item>
        <item>Iraq </item>
        <item>Ireland </item>
        <item>Israel </item>
        <item>Italy</item>
        <item>Ivory </item>
        <item>Jamaica </item>
        <item>Japan </item>
        <item>Jordan </item>
        <item>Kazakhstan </item>
        <item>Kenya </item>
        <item>Kiribati </item>
        <item>Korea-North</item>
        <item>Korea-South </item>
        <item>Kuwait </item>
        <item>Kyrgyzstan </item>
        <item>Laos </item>
        <item>Latvia </item>
        <item>Lebanon </item>
        <item>Lesotho </item>
        <item>Liberia </item>
        <item>Libya </item>
        <item>Liechtenstein </item>
        <item>Lithuania</item>
        <item>Luxembourg </item>
        <item>Macau</item>
        <item>Macedonia </item>
        <item>Madagascar </item>
        <item>Malawi </item>
        <item>Malaysia </item>
        <item>Maldives </item>
        <item>Mali </item>
        <item>Malta </item>
        <item>Marshall Islands </item>
        <item>Martinique (French) </item>
        <item>Mauritania </item>
        <item>Mauritius Port</item>
        <item>Mayotte </item>
        <item>Mexico </item>
        <item>Micronesia </item>
        <item>Moldova </item>
        <item>Monaco</item>
        <item>Mongolia</item>
        <item>Montenegro </item>
        <item>Montserrat </item>
        <item>Morocco</item>
        <item>Mozambique </item>
        <item>Myanmar</item>
        <item>Namibia </item>
        <item>Nauru </item>
        <item>Nepal </item>
        <item>Netherlands</item>
        <item>Netherlands Antilles</item>
        <item>New Caledonia (French)</item>
        <item>New Zealand </item>
        <item>Nicaragua </item>
        <item>Niger </item>
        <item>Nigeria </item>
        <item>Niue </item>
        <item>Norfolk Island </item>
        <item>Northern Mariana Islands </item>
        <item>Norway</item>
        <item>Oman </item>
        <item>Pakistan </item>
        <item>Palau </item>
        <item>Panama </item>
        <item>Papua New Guinea Port</item>
        <item>Paraguay </item>
        <item>Peru </item>
        <item>Philippines </item>
        <item>Poland</item>
        <item>Polynesia (French) </item>
        <item>Portugal </item>
        <item>Puerto Rico </item>
        <item>Qatar </item>
        <item>Reunion (French) </item>
        <item>Romania </item>
        <item>Russia </item>
        <item>Rwanda </item>
        <item>Saint Helena </item>
        <item>Saint Kitts &amp; Nevis Anguilla</item>
        <item>Saint Lucia </item>
        <item>Saint Pierre and Miquelon</item>
        <item>Saint Vincent &amp; Grenadines </item>
        <item>Samoa </item>
        <item>San Marino </item>
        <item>Sao Tome and Principe</item>
        <item>Saudi Arabia</item>
        <item>Senegal </item>
        <item>Serbia </item>
        <item>Seychelles </item>
        <item>Sierra Leone</item>
        <item>Singapore </item>
        <item>Slovakia </item>
        <item>Slovenia </item>
        <item>Solomon Islands</item>
        <item>Somalia</item>
        <item>South Africa </item>
        <item>Spain </item>
        <item>Sri Lanka </item>
        <item>Sudan</item>
        <item>Suriname</item>
        <item>Swaziland </item>
        <item>Sweden </item>
        <item>Switzerland</item>
        <item>Syria </item>
        <item>Taiwan </item>
        <item>Tajikistan</item>
        <item>Tanzania </item>
        <item>Thailand </item>
        <item>Togo </item>
        <item>Tokelau </item>
        <item>Tonga </item>
        <item>Trinidad and Tobago </item>
        <item>Tunisia </item>
        <item>Turkey </item>
        <item>Turkmenistan </item>
        <item>Turks and Caicos Islands</item>
        <item>Tuvalu </item>
        <item>U.K. </item>
        <item>USA </item>
        <item>Uganda </item>
        <item>Ukraine </item>
        <item>United Arab Emirates</item>
        <item>Uruguay </item>
        <item>Uzbekistan </item>
        <item>Vanuatu</item>
        <item>Vatican </item>
        <item>Venezuela</item>
        <item>Vietnam </item>
        <item>Virgin Islands (British) </item>
        <item>Virgin Islands (USA)</item>
        <item>Wallis and Futuna Islands</item>
        <item>Yemen</item>
        <item>Zambia </item>
        <item>Zimbabwe </item>

    </string-array>
</resources>

Add spinner in your activity's layout in front of your editext

  <Spinner
                    android:id="@+id/spinner"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/inner_img_xxxl"
                    android:dropDownWidth="220dp" />

set Adapter in activity to show all country codes along with name of countries.

   private void setDataToSpinner() {
        final ArrayList<String> countryCodeList = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.country_code)));
        final ArrayList<String> countryNameList = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.country_name)));

        ArrayAdapter<String> adp = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, countryCodeList) {

            @Override
            public View getDropDownView(int position, View convertView, ViewGroup parent) {
                View row = View.inflate(LoginActivity.this, R.layout.spinner_dropdown_view, null);
                TextView countrycodeTV = row.findViewById(R.id.countrycodeTV);
                TextView countrynameTV = row.findViewById(R.id.countrynameTV);

                countrycodeTV.setText(countryCodeList.get(position));
                countrynameTV.setText(countryNameList.get(position));

                AppController.getInstance().setTypefaceNeon(countrycodeTV);
                AppController.getInstance().setTypefaceNeon(countrynameTV);
                return row;
            }


            public View getView(int position, View convertView, ViewGroup parent) {
                View row = View.inflate(LoginActivity.this, R.layout.spinner_get_view, null);
                TextView countrycodeTV = row.findViewById(R.id.countrycodeTV);
                TextView countrynameTV = row.findViewById(R.id.countrynameTV);
                AppController.getInstance().setTypefaceNeon(countrycodeTV);
                AppController.getInstance().setTypefaceNeon(countrynameTV);
                countrycodeTV.setText(countryCodeList.get(position));
                countrynameTV.setText(countryNameList.get(position));
                return row;
            }
        };


        adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        binding.spinner.setAdapter(adp);}

create layout simple_spinner_item

<?xml version="1.0" encoding="utf-8"?>

    <TextView xmlns:android="http://schemas.android.com/apk/res/android" 
        android:id="@android:id/text1"
        style="?android:attr/spinnerItemStyle"
        android:singleLine="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ellipsize="marquee"
        android:textAlignment="inherit"/>

create layout spinner_get_view

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/countrycodeTV"
        style="?android:attr/spinnerItemStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="marquee"
        android:maxLines="1"
        android:textAlignment="inherit"
        android:textSize="@dimen/text_size_button_xs" />

    <TextView
        android:id="@+id/countrynameTV"
        style="?android:attr/spinnerItemStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_toEndOf="@+id/countrycodeTV"
        android:ellipsize="marquee"
        android:maxLines="1"
        android:textAlignment="inherit"
        android:textSize="@dimen/text_size_button_xs" />


</RelativeLayout>

Question:

Validate email format only if EditText is not blank in Android. And if the field is blank validation should not be check. I did not find any solution in this scenario which is useful for me.


Answer:

Try this code

final EditText emailEditTxt= (EditText)findViewById(R.id.text); 

String emailStr = emailEditTxt.getText().toString().trim();

if(emailStr!=null)

if(emailStr.length()>=1){

String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";


if (emailStr .matches(emailPattern))
{
Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
}
else 
{
Toast.makeText(getApplicationContext(),"Invalid email address", Toast.LENGTH_SHORT).show();
}
}