Search code examples
androidandroid-edittextuser-input

Checking user input from Edit Text in Android


I am trying to build a small game app for a school project. It should consist of two edit text fields and a button. In the first field, there should be two randomly generated numbers by the app. In the second field, a user should enter the sum of those two numbers. If the sum is correct, a toast will be displayed when the user clicks the button, saying "You guessed it". If it's not correct, then the toast will say "You did something wrong".

The part with the random numbers is working just fine. However, I simply cannot make it check what the user has entered in the second field. And because of that I can't write any onClick method for the button that would check whether the user has entered the correct sum of those two random numbers or not.

Any help or suggestion would be much appreciated, thanks!


Solution

  • But you don't really need the TextWatcher for what you want to do.

    Here's a simple guess-try of what you're trying to do.

    theButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int number1, number2;
                //figure out the numbers from the first edittext, i'm pressuming there's a space between the numbers
                String[] parts = firstEditText.getText().toString().split(' '); 
                number1 = Integer.valueOf(parts[0]);
                number2 = Integer.valueOf(parts[1]);
                //now we know the numbers, lets Toast whether the user was right or wrong
                int enteredNumber = Integer.valueOf(secondEditText.getText().toString());
                if(enteredNumber == (number1 + number2) ) {
                    Toast.makeText(getActivity(), "You guessed it right!", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getActivity(), "Something's not right...", Toast.LENGTH_SHORT).show();
                }
            }
        });