20

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.

Xiong Chiamiov
  • 11,582
  • 8
  • 55
  • 95

6 Answers6

34

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

gio
  • 4,671
  • 3
  • 27
  • 42
19

SpannableString is not String directly. so, you can not cast. but, it can be converted to string. you can convert something to string with concatenating with empty string.

pasteData = "" + item.getText();
Adem
  • 9,146
  • 8
  • 39
  • 57
  • Code-only answer is discouraged since it might confuse OP and future readers. Instead, explain what the code does. – Andrew T. Dec 15 '14 at 07:52
  • 18
    This is a work around, and does not address the root problem. The problem is that item.getText() returns a CharSequence, not a String. OP should use item.getText().toString() to convert the CharSequence to String – Aaron Dougherty Jan 31 '15 at 22:15
1

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

String htmlString = Html.toHtml(spannedText);
SilentKiller
  • 7,088
  • 6
  • 37
  • 74
0

It has worked for me String htmlString = String.valueOf(Html.fromHtml(contenttext,Html.FROM_HTML_MODE_COMPACT));

Manju S B
  • 61
  • 1
  • 4
0

This is what it worked for me in Kotlin:

val str = text.toString()
pableiros
  • 10,752
  • 11
  • 79
  • 78
0

You want to add attribute in Textview in xml file like this

add this -> android:bufferType="spannable"

example:

    <TextView
        android:id="@+id/self_assessment_intro2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:bufferType="spannable"
        android:text="@string/self_assessment_intro2"
        android:textSize="@dimen/self_assessment_intro_text_size" />
sdh4967
  • 21
  • 3