Add http://www. in the text if not Exist

做~自己de王妃 提交于 2019-12-03 08:28:45

You can do like this

String url = textView.getText().toString();
if(!url.startsWith("www.")&& !url.startsWith("http://")){
  url = "www."+url;
}
if(!url.startsWith("http://")){
  url = "http://"+url;
}

You can use this url to display content in WebView

Hope this will solve your problem

just modified @silwar answer and add https :

 if(!url.startsWith("www.")&& !url.startsWith("http://") && !url.startsWith("https://")){
        url = "www."+url;
    }
    if(!url.startsWith("http://") && !url.startsWith("https://")){
        url = "http://"+url;
    }

The most efficient way of checking that the domain name is well formed and contains (or not) a prefix, is using a regular expression.

Check out Java Pattern to match regex in Android. It is worth it.

I would just get the text from the TextView and parse it via startsWith(). If this is false, just add it to the text and use setText() to reasign it.

You might also want to check for other expressions like only "www.". So take a closer look at contains().

As Sebastien requested, regex is a good option. You can also get the text from the view, create an URI object

Uri uri = Uri.create(view.getText().toString());

then with uri.somemethod You should be able to get everything about an url you want to know. If the uri fails to create, you generate error messages cause something has gone wrong.

abhijeet kokane

Try this

String a = "http://";
webview.loadUrl(a + url.getText().toString());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!