Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k 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 Reply

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 



与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...