Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

kotlin - getString("android.text") returns SpannableString instead of String

I'm trying to get notification content using:

val sender = sbn.notification.extras.getString("android.title")
val msg = sbn.notification.extras.getString("android.text")

android.title returns the desired value, but android.text returns null.

Upon debugging, I found out:

W/Bundle: Key android.text expected String but value was a android.text.SpannableString. The default value <null> was returned.
W/Bundle: Attempt to cast generated internal exception:
java.lang.ClassCastException: android.text.SpannableString cannot be cast to java.lang.String

Why android.text is returning SpannableString? And how can I convert it to String in this case?

question from:https://stackoverflow.com/questions/65841242/getstringandroid-text-returns-spannablestring-instead-of-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Retrieving SpannableString

If you cannot control what is put in the intent extras you should be able to retrieve it with the following code:

val msg = sbn.notification.extras.getCharSequence("android.text").toString()

Note that SpannableString class extends CharSequence.

Adding extras

Wherever you are adding the extras make sure that you do not add a SpannableString but the string itself!

For example, for an editText:

var editText: EditText = ...

extras.put("android.text", editText.text) // this will put an Editable which is a Spannable and not a string

extras.put("android.text", editText.text.toString()) // this puts a string 



与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.5k users

...