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

user4356416 picture user4356416 · Dec 15, 2014 · Viewed 23.6k times · Source

When copying String from any browser page, pasteData works properly. However when copying SpannedString from a message sent item editor(field), the application crashes and shows this error message:

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

My code:

// 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 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.

Answer

gio picture gio · Dec 15, 2014

From CharSequence.toString()

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

You need to use next code.

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

You can not cast to android.text.SpannableString because item.getText() returns CharSequence, there are a lot of implementations of it