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

So, I looked at the getText () method, and I found out that it returns CharSequence. Therefore, you cannot just do this:

TextView myTextView = (TextView) findViewById(R.id.my_text_view); String myString = myTextView.getText(); 

And instead, you need to convert the returned CharSequence to String by doing the following:

 TextView myTextView = (TextView) findViewById(R.id.my_text_view); String myString = myTextView.getText().toString(); 

Here is my question: can you just do this instead ?:

 TextView myTextView = (TextView) findViewById(R.id.my_text_view); String myString = (String) myTextView.getText(); 

I tried this in my code and it worked fine, but everyone seems to be using the first method. So is there a problem that I do not see with my way of doing this? Or is it just another way to do this, and if so, what are the advantages of both?

Thanks for your answers in advance :)

+7
java android
source share
1 answer

So is there a problem that I do not see with my way of doing this?

It will fire with a ClassCastException if the returned CharSequence not String . For example, if you use Html.fromHtml() or other SpannedString creation SpannedString and use this in a TextView , getText() will not return a String .

+11
source share

All Articles