1

I am using the following code to open default browser if links are external. But so far I can only add two domains (or names). How can I add more ? If the link contains the word "facebook" it will open out side the app. I want to add more names/doamins in there.

if (url.contains("facebook") || url.contains("flipkart")) {
    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
    startActivity(intent)
    webView.goBack()
    return true
} else {
    view?.loadUrl(url)
}

already tried

if (url.contains("facebook,youtube") || url.contains("flipkart")) {

and

if (url.contains("facebook","youtube") || url.contains("flipkart")) {

The only working method I got is following, is there a better option?

if (url.contains("facebook") || url.contains("flipkart") || url.contains("youtube")) {
Gautham M
  • 4,816
  • 3
  • 15
  • 37
Shij Thach
  • 93
  • 7

2 Answers2

1

You can add more by adding more OR operators like this:

if (url.contains("facebook") || url.contains("flipkart") || 
    url.contains("youtube")) {

If things are getting messier, you can create an ArrayList:

ArrayList<String> domains = new ArrayList<String>();
domains.add("facebook");
domains.add("flipkart");
domains.add("youtube");

Then create a function:

private boolean checkDomain(){
  for(String domain: domains){
    if (url.contains(domain)){
      return true;
    }
  }
  return false;
}

And use it in your if statement:

if(checkDomain(url)){
   //Open URL in external browser
} else {
   //Display URL in your webview
}
Lee Boon Kong
  • 1,007
  • 1
  • 8
  • 17
0

You can create an ArrayList or String array,

String[] items = {"facebook", "flipkart", "stackoverflow"};
String url = "https://stackoverflow.com/questions/8992100/";

Then create a check function :

public static boolean checkUrls(String inputStr, String[] items) {
    return Arrays.stream(items).anyMatch(inputStr::contains);
}

And use this method in your if statement:

if( checkUrls(url)){
    //Open URL in out side the app
} else {
    //Display URL in your app
}
lookub
  • 56
  • 4