So, I've been looking at the getText() method and I've learned, that it returns a CharSequence. So you can't just do this:
TextView myTextView = (TextView) findViewById(R.id.my_text_view);
String myString = myTextView.getText();
And instead, have to convert the returned CharSequence into a String by doing this:
TextView myTextView = (TextView) findViewById(R.id.my_text_view);
String myString = myTextView.getText().toString();
Here comes my question: Can't you just do this instead?:
TextView myTextView = (TextView) findViewById(R.id.my_text_view);
String myString = (String) myTextView.getText();
I've tried this in my code and it worked perfectly fine, but everyone seems to be using the first way.. So is there a problem I'm not seeing with my way of doing it? Or is it just a different way to do it and if so, what are the benefits of both ways?
Thanks for your answers in advance :)
GetText returns the text from the single-line text field. It returns only the first line of a multi-line text field. If you include iStartChar but not iNumChars , GetText returns the text from the iStartChar character to the end of the text.
it actually returns Editable and not CharSequence but you can store it in a String variable by calling toString() on it.
So is there a problem I'm not seeing with my way of doing it?
It will crash with a ClassCastException
if the CharSequence
that is returned is not a String
. For example, if you use Html.fromHtml()
or other means of creating a SpannedString
, and use that in the TextView
, getText()
will not return a String
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With