Search code examples
androidstringandroid-notificationsspannablestring

Cannot read notification which contains SpannableString instead of regular String


Situation:

I have code that is reading the text of a notification

String notificationText = sbn.getNotification().extras.getString("android.text");

and it causes the following error when a notification with special characters is read:

Key android.text expected String but value was a android.text.SpannableString.  
The default value <null> was returned. 
java.lang.ClassCastException: android.text.SpannableString cannot be cast to java.lang.String

The particular text that caused this error was a notification from com.whatsapp with the text: "bold text regular text"

Note that some characters are in bold. (no exception is thrown without the bold).

Question:

Is there a way for me to get this text as a string?

I have already unsuccessfully tried:

  • Casting it to a string.
  • Looking for a different method other than getString to get the text from extras
  • Adding a " " to the end of the string
  • Checking if the function is returning a SpannableString with 'instanceof', then casting it to a SpannableString

Solution

  • In my case struggled almost 3 hrs

    String.valueOf(sbn.getNotification().extras.get("android.text"));
    

    worked like a charm