1

I made a button invisble in xml, I want to make button visible again when a certain string value in my EditText is made. I have used TextWatcher check when the value is met using an if statement. However when the code to reveal the button is executed the application crashes saying textwatcher stopped working. I'm pretty new to android developing so it's probably me screwing up.

Here is my code:

public class MainActivity extends AppCompatActivity
{
    private EditText UserInput;
    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = (Button)findViewById(R.id.button);
        UserInput = (EditText) findViewById(R.id.UserInput);
        UserInput.addTextChangedListener(watch);
    }

    TextWatcher watch = 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().equals("teststring") ){
                //program crashes when it reaches this part
                button.setVisibility(View.VISIBLE);
            }
            else 
            {

            }
        }
        @Override
        public void afterTextChanged(Editable s) {

        }
    };      
}
PEHLAJ
  • 9,980
  • 9
  • 41
  • 53

2 Answers2

1

You already defined your Button as Global variable here:

private Button button;

But when you define views inside onCreate method you define a Local variable Button and instantiate it, here:

Button button = (Button)findViewById(R.id.button);

Later when you call setVisibility on Button, you calling this method on the Global variable one that wasn't instantiated.. To solve this issue simple change your onCreate method like this:

button = (Button)findViewById(R.id.button);

So the Global variable get instantiated.

Keivan Esbati
  • 3,376
  • 1
  • 22
  • 36
0

Change this line

Button button = (Button)findViewById(R.id.button);

to

button = (Button)findViewById(R.id.button);

So that class member button get initialized

PEHLAJ
  • 9,980
  • 9
  • 41
  • 53