Why show java.lang.ClassCastException: android.text.SpannableString cannot be added to java.lang.String?

When copying a String from any browser page, pasteData works correctly. However, when copying a SpannedString from the sent messages editor (fields), the application crashes and displays this error message:

 java.lang.ClassCastException: android.text.SpannableString cannot be cast to java.lang.String 

My code is:

 // since the clipboard contains plain text. ClipData.Item item = clipBoard.getPrimaryClip().getItemAt(0); // Gets the clipboard as text. String pasteData = new String(); pasteData = (String) item.getText(); 

where the ClipboardManager instance is defined as clipBoard , below:

 clipBoard = (ClipboardManager) context.getSystemService(context.CLIPBOARD_SERVICE); clipBoard.addPrimaryClipChangedListener(new ClipboardListener()); 

All I'm trying to do is use pasteData in String format. How to get rid of this error? Any help is appreciated.

+12
java android string clipboard spannablestring
source share
4 answers

SpannableString is not a string directly. so you cannot quit. but it can be converted to a string. you can convert something to a string with concatenation by an empty string.

 pasteData = "" + item.getText(); 
+16
source share

From CharSequence.toString ()

Returns a string with the same characters in the same order as in this sequence.

You need to use the following code.

 String pasteData = item.getText().toString(); 

You cannot use android.text.SpannableString because item.getText() returns CharSequence , there are many implementations of it

+30
source share

If your Spanned text contains only HTML content, you can convert it using Html.toHtml()

 String htmlString = Html.toHtml(spannedText); 
0
source share

I have it String htmlString = String.valueOf(Html.fromHtml(contenttext,Html.FROM_HTML_MODE_COMPACT));

0
source share

All Articles