0

I want to check if user input is equal to the array, if not toast error message when pressing a button. I am not sure if I should check input outside the button and then use an if !equals inside button to toast the message. Here is my attempt

I have this array in strings.xml

<string-array name="people">
        <item>JHON</item>
        <item>MARIE</item>
        <item>ALBERT</item>
        <item>ALEX</item>
    </string-array>

Activity.java:

String[] peopleArr =getResources().getStringArray(R.array.people);
EditText userinput=findViewById(R.id.editTextUserinput);

Button find = findViewById(R.id.findBtn);
        find.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            for (int i = 0; i <= peopleArr.length - 1; i++) {
                    if (!userinput.getText().toString().equals(peopleArr[i])) {
                        
                        Toast.makeText(getApplicationContext(), "Invalid user", Toast.LENGTH_SHORT).show();
                    }
                }
}

This is wrong because it is toasting invalid user 4 times when the button is pressed.

comms
  • 3
  • 1
  • https://stackoverflow.com/questions/1128723/how-do-i-determine-whether-an-array-contains-a-particular-value-in-java – Arno den Hond Jan 27 '22 at 15:49
  • There might be several problems. I think most of them will be associated what did you entered in the EditText. "JHON" is not equal to "JOHN" and not even "JHON " or " JHON". Otherwise you can use the Activity fields even in listeners. – Simon Harvan Jan 27 '22 at 15:53

1 Answers1

0

this code check user, if can finde user will Toast: Valid User otherwise will Toast: Invalid User

 String[] peopleArr =getResources().getStringArray(R.array.people);
EditText userinput=findViewById(R.id.editTextUserinput);

Button find = findViewById(R.id.findBtn);
    find.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Boolean userIsFounded = false;
        for (int i = 0; i <= peopleArr.length - 1; i++) {
            if (userinput.getText().toString().equals(peopleArr[i])) {
                userIsFounded = true;
                break;
            }
        }
        String message  =  (userIsFounded)? "Valid User":"InValid User";
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();

    }
soheil ghanbari
  • 388
  • 1
  • 7