Reputation: 25
What is the difference? Aren't they actually the same thing?
I'm getting "Cannot resolve method 'getText' in 'View'"
string = findViewById(R.id.signup_email).getText().toString();
But it's working perfectly.
textView = findViewById(R.id.signup_email);
string = textView.getText().toString();
Upvotes: 0
Views: 107
Reputation: 2250
you can do something like this
((TextView)findViewById(R.id.signup_email)).getText().toString();
if you do just findViewById
you will get View
as the returned Object which is the parent of TextView
but have a limited method to work with. So if we know what type of our view is we should cast the Object to the correct view intended So we can perform a variety of operation specific to that view.
In this case, it's TextView
that is the reason we cast it to it and then we are able to use the getText()
method of TextView Class which was not available in the View
class hence you were getting compilation error for the usage of that method.
Upvotes: 1
Reputation: 305
findViewById() returns a View. So the view does not heve getText() method. So if you modify the first option as follows:
string = ((TextView)findViewById(R.id.signup_email)).getText().toString();
With this, it will cast view to TextView and than you can call get text method.
Upvotes: 0
Reputation: 967
First of all findViewById(R.id.signup_email)
returns the View
object, so when you write this statement findViewById(R.id.signup_email).getText()
here getText()
applies on view
object (apparently View
class does not contain this method).
But when you separate in two lines, here textView = findViewById(R.id.signup_email);
the View
object will be type cast to TextView
or EditText
(which you defined) object. so from here you will get this method.
If you want to keep in single line you can use
string = ((TextView) findViewById(R.id.signup_email)).getText().toString();
Upvotes: 1