Question

I am making an android application. I have a TextField and a button. Based on the value of the textfield, as soon as the user clicks the button I want to make something. I have the code:

EditText et = (EditText)findViewById(R.id.editText1);
String value = et.getText().toString();
ImageButton ib = (ImageButton)findViewById(R.id.imageButton1);
ib.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (value = "a" ) {
            //do something }
            }
        });

This however doesn't compile, saying "Cannot refer to a non-final variable value inside an inner class defined in a different method". Is there any way to fix this? Thanks a lot

Was it helpful?

Solution

Use final String value = et.getText().toString();

and then use, if(value.equals("a") { }

OTHER TIPS

If you want to compare the value of a string you should use the "equals" method instead of "=".

The code will look like this:

EditText et = (EditText)findViewById(R.id.editText1);
final String value = et.getText().toString();
ImageButton ib = (ImageButton)findViewById(R.id.imageButton1);

ib.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (value.equals("a") ) {
           //do something }
        }
    });
final String value = et.getText().toString();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top