Html tags are used to define how contents of a webpage should be formatted and displayed. Sometimes the SUSI answer type response contains some html tags but showing these html tags without parsing would distort the normal text flow in SUSI Android.
For the query ‘Ask me something’ SUSI’s reply is
“data”: [ { “question”: “Which soccer team won the Copa América 2015 Championship ? “, }] |
In SUSI Android this message looks like
As you can see that showing html tags without parsing distort the normal text flow. So we need to parse html tags properly. We use Html class for this purpose. Html class is present in android.text package and you can import it in the class where you want to use it.
import android.text.Html |
fromHtml method of Html class is used to parse html tags. But for API level less than 24 and equal to or greater than 24 we use different parameters in fromHtml method.
For API level less than 24 we used
Html.fromHtml(model.getContent()) |
But for API level equal to or greater than 24 we have to use
Html.fromHtml(model.getContent(), Html.FROM_HTML_MODE_COMPACT) |
Here the second parameter is legacy flags which decides how text inside a tag will be shown after parsing.
In case of Html.fromHtml(String string) legacy flag is by default FROM_HTML_MODE_LEGACY. It indicates that separate block-level elements with blank lines.
So after parsing html tags using fromHtml
But return type of fromHtml method is Spanned so if you need String then you have to convert it into string using toString() method.
Anchor action type in susi response contains link and text.
“link”: “https://www.openstreetmap.org/#map=13/1.2896698812440377/103.85006683126556”, “text”: “Link to Openstreetmap: Singapore” |
Here the text is the text we show in textview and link is used to show web content in the browser when user click on text. So first link and text are attached together like
“<a href=\”” +susiResponse.getAnswers().get(0).getActions().get(i).getAnchorLink() + “\”>” + susiResponse.getAnswers().get(0).getActions().get(1).getAnchorText() + “</a>” |
Here text between the tag is description of link and after parsing we show this text in textview. It can be parsed using fromHtml method of Html class and textview is made clickable by
chatTextView.setMovementMethod(LinkMovementMethod.getInstance()); |
Resources
- Main site link of Html class: https://developer.android.com/reference/android/text/Html.html
- Blog link on how to show an Html string in an Android textview: http://alvinalexander.com/android/how-show-html-string-in-android-textview-webview