lBartimeusl
lBartimeusl

Reputation: 75

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

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

Upvotes: 7

Views: 11337

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007276

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.

Upvotes: 11

Related Questions