Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getText().toString() vs (String) getText()

Tags:

java

android

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 :)

like image 863
lBartimeusl Avatar asked Jan 24 '17 17:01

lBartimeusl


People also ask

What is use of GetText () method?

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.

What is the return type of GetText () method?

it actually returns Editable and not CharSequence but you can store it in a String variable by calling toString() on it.


1 Answers

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.

like image 56
CommonsWare Avatar answered Nov 07 '22 14:11

CommonsWare