2

I can't get data from an EditText fr1. I type some text into fr1, press a Button btn and nothing happens. TextView result is empty. Why is it empty? What do I do wrong? Thanks.

public class MainActivity extends Activity{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EditText fr1 = (EditText) findViewById(R.id.fraction1);
        final TextView result = (TextView) findViewById(R.id.result);
        Button btn = (Button) findViewById(R.id.getresult);

        final String s = fr1.getText().toString();

        btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // TODO Auto-generated method stub
                result.setText(s);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

2 Answers 2

4

Change this

final String s = fr1.getText().toString();
btn.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        // TODO Auto-generated method stub
        result.setText(s);
    }
});

to

btn.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        final String s = fr1.getText().toString();
        result.setText(s);
    }
});

The reason you need to change is you are not getting the text from the EditText on the Button click rather before the click of the Button (right in the onCreate()) where the EditText would probably have empty String as text. So you are not able to print what you type. Now you can find the problem solved by getting the text from the EditText in the onClick()

0
3

You need to retrieve the text at the moment the button is clicked rather than straight after inflating the EditText. In the latter case, the typed text will not be available yet.

Move

String s = fr1.getText().toString();

into the button's OnClickListener and you should be good to go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.