Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check first 2characters of String in Android

Tags:

java

android

In my application, I want to get a phone number from the user and if the first 2 characters of this number are 09, I want to show Toast.
I wrote the code below, but it always shows me the Toast message.
My code:

    phoneNumberPage_phoneEdtTxt.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.toString().length() < 11) {
                enableDisableBtn(0.3f, false);
            } else {
                hideKeyboard(activity);
                enableDisableBtn(1.0f, true);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.toString().trim().length()==1){
                if (!s.equals("0")){
                    Toast.makeText(context, "NOOOOOO", Toast.LENGTH_SHORT).show();
                }
            }
        }
    });
}

How can I do it? Can you please help me?

like image 440
Hock Avatar asked Dec 04 '25 23:12

Hock


1 Answers

using startsWith

if(s.startsWith("09")){

or you can use matches with regex

if(s.matches("09(.*)"))
like image 95
Nuwan Alawatta Avatar answered Dec 06 '25 13:12

Nuwan Alawatta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!