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

5.1k views Asked by At
String s = extras.getString("android.text");

I am trying to read values from a bundle. But I don't exactly know the type of value I am trying to read. When I try to read it using getString I get following error

java.lang.ClassCastException: android.text.SpannableString cannot be cast to java.lang.String
at android.os.BaseBundle.getString(BaseBundle.java:921)
at com.example.myapp.services.NLService.constructNotificationObject(NLService.java:67)
at com.example.myapp.services.NLService.onNotificationPosted(NLService.java:100)

What exactly is the type of the value? And how can I get it in string format?

Edit: The bundle I am trying to read from is not created by me. So I can't control what is passed in the bundle. The type of the value is SpannableString but getString tries to cast it to String which produces the error. It seems this question is duplicate of this one. One workaround is to do this ((SpannableString)extras.get("android.text")).toString()

2

There are 2 answers

0
Bidhan On

You've probably passed a SpannableString through your intent. You cannot cast it directly to a string. Try this instead

String s = extras.getString("android.text") + "";
0
sourabh devpura On

You need to read file line by line and buil String by StringBuilder

try (BufferedReader br = new BufferedReader(new FileReader(file))) {
   StringBuilder sb = new StringBuilder();
    while ((line = br.readLine()) != null) {
       sb.append(line);
    }
}

You can read the data faster if you assume there is no character encoding. e.g. ASCII-7 but it won't make much difference. It is highly likely that what you do with the data will take much longer.

A less common pattern to use which avoids the scope of line leaking.

  try(BufferedReader br = new BufferedReader(new FileReader(file))) {
StringBuilder sb = new StringBuilder();
        for(String line; (line = br.readLine()) != null; ) {
           sb.append(line);
        }
        // line is not visible here.
    }