Recently I’ve been working on show notes support for SwallowCatcher. Since most podcast feeds include their show notes in the feed as embedded HTML I decided to render this HTML to display the show notes. This turned out to be ridiculously simple thanks to Android’s WebView class. The API for rendering arbitrary HTML within your app is almost Pythonic in its simplicity. However, there are a couple of gotchas which caught me out, so I decided to cover them here.
I started out by creating a new Activity class and a layout XML file for it. The layout XML was taken almost directly from the Android WebView Tutorial page:
<?xml version="1.0" encoding="utf-8"?> <WebView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/shownotes" android:layout_width="fill_parent" android:layout_height="fill_parent" />
In my Activity class the XML is loaded as normal. We also need to import the WebView class and the URLEncoder class. Additionally, the UnsupportedEncodingException class is required:
import android.webkit.WebView; import java.net.URLEncoder; import java.io.UnsupportedEncodingException;
Next, we need to encode the text in the correct format. Weirdly, WebView requires that the text is URL escaped, but without spaces converted to ‘+’ symbols. I used URLEncoder to encode my content then replaced the ‘+’ symbols with spaces. This probably isn’t perfect, but for my purposes it works.
String text = "<html><head></head><body>Content goes here!</body></html>"; text = URLEncoder.encode(text, "utf-8"); text = text.replace('+', ' ');
Finally, we find the WebView from the XML and tell it to load the string as its content:
WebView web = (WebView)findViewById(R.id.shownotes); web.loadData(text, "text/html", "utf-8");
All the above is encased in a try..catch statement for UnsupportedEncodingException, just in case the URLEncoder has a fit. That’s pretty much it. In SwallowCatcher the ShowNotesActivity is 56 lines, including all the verbose Java imports and bootstrapping and loading the content from the database via ORMLite.
As a wise action hero (and ex-Jedi) once said, “I love it when a plan comes together”.