Search code examples
javaandroidandroid-webview

How to check whether we should go to google search or just simple load url


I am new to Android. I got stuck in such a small problem. I have edittext in my fragment. I want whatever user enter in edittext it should search on google. But whenever he enters any url then just simply load url in webview. I don't know how to check whether edittext contains url or not.

Here is my code, but it is not working:

String value = getIntent().getStringExtra("searchvalue");
        if(URLUtil.isValidUrl(value) && Patterns.WEB_URL.matcher(value).matches()){
            url = value;
        }else {
            url = Uri.parse("https://www.google.com/#q=" +
                    value).toString();
        }

This code is not working. It is everytime searching on google whether i am entering url or any random value. Please help me.


Solution

  • This code looks really good. Perhaps the only missing thing is to include domains in addition to URLs. Just try appending HTTP:// in front of the value, something like this:

    String value = getIntent().getStringExtra("searchvalue");
            if(URLUtil.isValidUrl(value) && Patterns.WEB_URL.matcher(value).matches()){
                url = value;
            }
            else if(URLUtil.isValidUrl("http://" + value) && Patterns.WEB_URL.matcher("http://" + value).matches()){
                url = "http://" + value;
            }
    else {
                url = Uri.parse("https://www.google.com/#q=" +
                        value).toString();
            }