1

How come this doesn't work:

 String btnText = ((Button)findViewById(R.id.my_Button).getText().toString();

But this does:

Button myButton = ((Button)findViewById(R.id.my_Button);
String btnText = myButton.getText().toString(); 

The getText() method can't resolve, but I'm not sure why when essentially these two line are the same.

1
  • 2
    You have to put one more closing small bracket after this : (R.id.my_Button) like - ((Button)findViewById(R.id.my_Button)) then you access Button getText() method. Commented May 1, 2015 at 5:03

3 Answers 3

2

It cant find the method getText() because you are trying to call it from an Object type which was returned by the method findViewById

You forgot to add another layer of bracket to fully cast it as a Button to enable you to call the method getText()

String btnText = ((Button)findViewById(R.id.my_Button)).getText().toString();

For the second example you directly cast it and reference to an Button object therefore you can directly call getText method from the button object itself

Sign up to request clarification or add additional context in comments.

Comments

2

Forgot the brackets,

String btnText = ((Button)findViewById(R.id.my_Button)).getText().toString();

Comments

2

After converting find view reference to Button then you can access getText() method of Button :

After adding closing small bracket :

String btnText = ((Button)findViewById(R.id.my_Button)).getText().toString();

1 Comment

@LeonKowalski,Glad to help you.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.