My app allows users to type messages to other users while using limited HTML. One of the things I allow is the use of hyperlinks.
Example:
<a href="www.google.com">Google</a>
I am populating the TextView
via the following method:
txtview.setMovementMethod(LinkMovementMethod.getInstance());
txtview.setText(Html.fromHtml(items.get(position).getBody()));
If the user creates a hyperlink without prefixing http
to the url, the application crashes with the following exception:
FATAL EXCEPTION: main
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=www.google.com (has extras) }
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1545)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1416)
If the url is prefixed with http
, everything works fine.
Example:
<a href="http://www.google.com">Google</a>
How can I prevent this from happening?
The problem is that Html.fromHtml()
creates URLSpan
instances for embedded URLs, and this class "blindly" calls startActivity()
with the supplied url. This crashes whenever the URL does not match with any registered activity.
The problem is well explained in this CommonsWare post. The solution/example there overrides onClick()
and handles the ActivityNotFoundException
to prevent the crash.
If what you want to do is to be more permissive about the link instead, you could override getURL()
instead, for example as follows:
@Override
public String getURL()
{
String url = super.getURL();
if (!url.toLowerCase().startsWith("http"))
url = "http://" + url;
return url;
}
Note that this a very crude example (e.g. it does not account for "https" links) -- improve as needed!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With