Reputation: 424
In my application I receive a URL inserted by the user. This URL can be - for example - xx.sd
. Using any web browser, this URL is a valid URL, but when try to open it by intent, a crash happens: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=xx.sd }
.
I check this URL is valid URL by using this
Patterns.WEB_URL.matcher(model.getTarget().getUrl()).matches()
and open intent by using this code
Intent i = new Intent(Intent.ACTION_VIEW).setData(Uri.parse(model.getTarget().getUrl()));
itemView.getContext().startActivity(i);
I know i can solve this issue by append http
or https
before URL if not exist but if my URL start with another protocol like ftp
or file
and other protocols. Can any one help me to handle this issue.
Upvotes: 2
Views: 26834
Reputation: 862
Add un try-catch and call-again, such as:
public boolean startOpenWebPage(String url) {
boolean result = false;
if (!url.startsWith("http://") && !url.startsWith("https://"))
url = "http://" + url;
Uri webpage = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
try {
startActivity(intent);
result = true;
}catch (Exception e){
if (url.startsWith("http://")){
startOpenWebPage(url.replace("http://","https://"));
}
}
return result;
}
Upvotes: 0
Reputation: 3622
As you said this issue is really related to not well-formatted URL.
You can check for the ACTION_VIEW intent for the URL. First, this resolveActivity function check is there any application exists which can load URL. This will resolve the crash issue.
public void openWebPage(String url) {
Uri webpage = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}else{
//Page not found
}
}
OR, you can manage this by exception handling:
public void openWebPage(String url) {
try {
Uri webpage = Uri.parse(url);
Intent myIntent = new Intent(Intent.ACTION_VIEW, webpage);
startActivity(myIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "No application can handle this request. Please install a web browser or check your URL.", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
Upvotes: 10