51

I want to load the URL in WebView

I have used the following Code:

webView = (WebView) findViewById(R.id.webview1);
webView.setWebViewClient(new HostsWebClient());
webView.getSettings().setPluginState(PluginState.ON);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false);
webView.getSettings().setPluginsEnabled(true);
webView.getSettings().setSupportMultipleWindows(false);
webView.getSettings().setSupportZoom(false);
webView.setVerticalScrollBarEnabled(false);
webView.setHorizontalScrollBarEnabled(false);

webView.loadUrl(URL);

But when I execute it, I'm not able to load the url. I am getting web page not available.

Could anyone help?

Edward Falk
  • 9,578
  • 8
  • 66
  • 105
String
  • 3,462
  • 9
  • 39
  • 63

11 Answers11

113

Did you added the internet permission in your manifest file ? if not add the following line.

 <uses-permission android:name="android.permission.INTERNET"/> 

hope this will help you.

EDIT

Use the below lines.


    public class WebViewDemo extends Activity {


        private WebView webView;


        Activity activity ;
        private ProgressDialog progDailog; 

        @SuppressLint("NewApi")
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            activity = this;

            progDailog = ProgressDialog.show(activity, "Loading","Please wait...", true);
            progDailog.setCancelable(false);



           webView = (WebView) findViewById(R.id.webview_compontent);



           webView.getSettings().setJavaScriptEnabled(true);     
           webView.getSettings().setLoadWithOverviewMode(true);
           webView.getSettings().setUseWideViewPort(true);        
            webView.setWebViewClient(new WebViewClient(){

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    progDailog.show();
                    view.loadUrl(url);

                    return true;                
                }
                @Override
                public void onPageFinished(WebView view, final String url) {
                    progDailog.dismiss();
                }
            });

            webView.loadUrl("http://www.teluguoneradio.com/rssHostDescr.php?hostId=147");

           }
    }
Ghayoor ul Haq
  • 168
  • 1
  • 11
itsrajesh4uguys
  • 4,420
  • 3
  • 18
  • 31
  • 4
    You saved my life. Thank you. Nice and clean code. i also learnt how easy it is to make a simple progress bar. – CodeShadow Aug 26 '15 at 06:05
  • 1
    it's better to add Handler.post(hideDialog, 300) to not have blinking dialog – Eir Nym Dec 01 '15 at 14:13
  • You are a god among men. – Pierre P. Apr 13 '17 at 21:35
  • @deprecated Use {@link #shouldOverrideUrlLoading(WebView, WebResourceRequest) shouldOverrideUrlLoading(WebView, WebResourceRequest)} instead. – yoline Oct 28 '20 at 04:03
  • In shouldOverrideUrlLoading() method, do not call WebView#loadUrl(String) with the request's URL and then return true. This unnecessarily cancels the current load and starts a new load with the same URL. The correct way to continue loading a given URL is to simply return false, without calling WebView#loadUrl(String). And this method may be called for subframes and with non-HTTP(S) schemes; calling WebView#loadUrl(String) with such a URL will fail. – yoline Oct 28 '20 at 04:10
19

Add Permission Internet permission in manifest.

as <uses-permission android:name="android.permission.INTERNET"/>

This code it working

  public class WebActivity extends Activity {
  WebView wv;

 String url="http://www.teluguoneradio.com/rssHostDescr.php?hostId=147";

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_web);
    wv=(WebView)findViewById(R.id.webUrl_WEB);



WebSettings webSettings = wv.getSettings();
    wv.getSettings().setLoadWithOverviewMode(true);
    wv.getSettings().setUseWideViewPort(true);
    wv.getSettings().setBuiltInZoomControls(true);
    wv.getSettings().setPluginState(PluginState.ON);


    wv.setWebViewClient(new myWebClient());

    wv.loadUrl(url);
}




public class myWebClient extends WebViewClient {
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        // TODO Auto-generated method stub
        super.onPageStarted(view, url, favicon);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // TODO Auto-generated method stub

        view.loadUrl(url);
        return true;

    }
}
Rank
  • 890
  • 9
  • 17
18

maybe SSL

    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
        // ignore ssl error
        if (handler != null){
            handler.proceed();
        } else {
            super.onReceivedSslError(view, null, error);
        }
    }
wanpen
  • 356
  • 2
  • 2
14

Note : Make sure internet permission is given.

In android 9.0,

Webview or Imageloader can not load url or image because android 9 have network security issue which need to be enable by manifest file for all sub domain. so either you can add security config file.

  1. Add @xml/network_security_config into your resources:

<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="true">www.google.com</domain>
    </domain-config>
</network-security-config>
  1. Add this security config to your Manifest like this:

<application
   
    android:networkSecurityConfig="@xml/network_security_config"
    ...>
</application>

if you want to allow all sub domain

<application
   android:usesCleartextTraffic="true"
    ...>
</application>

Note: To solve the problem, don't use both of point 2 (android:networkSecurityConfig="@xml/network_security_config" and android:usesCleartextTraffic="true") choose one of them

Catarina
  • 329
  • 1
  • 12
Yogendra
  • 3,633
  • 1
  • 19
  • 18
  • 2
    Note: To solve the problem, don't use both of point 2 (`android:networkSecurityConfig="@xml/network_security_config"` and `android:usesCleartextTraffic="true"`) choose one of them. I couldn't open a url on android over 25 because I had both inserted in android manifest. :) – Catarina Jan 13 '20 at 15:46
  • generaly remove android:networkSecurityConfig="@xml/network_security_config" because what url you will open you dont know in live apk so if you are sure for domain then mention in network_security_config as sub domain otherwise remove android:networkSecurityConfig – Yogendra Feb 17 '20 at 04:18
  • i am facing the issue like below: i have 2URLs the 1st url is not laod in Webview but when i click on 2nd url then try to load firs url at that time its; working fine. -But every time i need to clikc on 2nd then 1st please share me what the issue? – Arbaz.in Aug 24 '20 at 05:08
  • Add sub domain in your network security config file – Yogendra Aug 24 '20 at 05:13
  • @Yogendra i added sub domain name in that file still facaing the same issue at this time no webbview is loadded – Arbaz.in Aug 24 '20 at 05:38
  • @Yogendra actually issue with my desing side now it's working perfect thanks!! – Arbaz.in Aug 24 '20 at 06:27
  • 1
    @Arbaz.in Cool. Hope it will help u. http://blogs.datanapps.com/ – Yogendra Aug 24 '20 at 07:01
7

First, check if you have internet permission in Manifest file.

<uses-permission android:name="android.permission.INTERNET" />

You can then add following code in onCreate() or initialize() method-

final WebView webview = (WebView) rootView.findViewById(R.id.webview);
        webview.setWebViewClient(new MyWebViewClient());
        webview.getSettings().setBuiltInZoomControls(false);
        webview.getSettings().setSupportZoom(false);
        webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webview.getSettings().setAllowFileAccess(true);
        webview.getSettings().setDomStorageEnabled(true);
        webview.loadUrl(URL);

And write a class to handle callbacks of webview -

public class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                           //your handling...
                return super.shouldOverrideUrlLoading(view, url);
        }
    }

in same class, you can also use other important callbacks such as -

- onPageStarted()
- onPageFinished()
- onReceivedSslError()

Also, you can add "SwipeRefreshLayout" to enable swipe refresh and refresh the webview.

<android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipeRefreshLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <WebView
            android:id="@+id/webview"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </android.support.v4.widget.SwipeRefreshLayout>

And refresh the webview when user swipes screen:

SwipeRefreshLayout mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
            mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mSwipeRefreshLayout.setRefreshing(false);
                            webview.reload();
                        }
                    }, 3000);
                }
            });
DsD
  • 923
  • 6
  • 10
5

Use the following things on your webview

webview.setWebChromeClient(new WebChromeClient());

then implement the required methods for WebChromeClient class.

vinoth
  • 215
  • 3
  • 9
1

Just as an alternative solution:

For me webView.getSettings().setUserAgentString("Android WebView") did the trick.

I already had implemented INTERNET permission and WebViewClient as well as WebChromeClient

mad_manny
  • 1,011
  • 15
  • 26
1

The simplest solution is to go to your XML layout containing your webview. Change your android:layout_width and android:layout_height from "wrap_content" to "match_parent".

  <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/webView"/>
1

In my Case, Adding the below functions to WebViewClient fixed the error. the functions are:onReceivedSslError and Depricated and new api versions of shouldOverrideUrlLoading

        webView.setWebViewClient(new WebViewClient() {

        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            Log.i(TAG, "loading: deprecation");
            return  true;
            //return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        @TargetApi(Build.VERSION_CODES.N)
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            view.loadUrl(request.getUrl().toString());
            Log.i(TAG, "loading: build.VERSION_CODES.N");
            return true;
            //return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onPageStarted(
                WebView view, String url, Bitmap favicon) {
            Log.i(TAG, "page started:"+url);
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, final String url) {

            Log.i(TAG, "page finished:"+url);

        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError er) {
            handler.proceed();
        }

    });
Hamid
  • 1,226
  • 1
  • 17
  • 30
1

Use this it should help.

 var currentUrl = "google.com" 
 var partOfUrl = currentUrl.substring(0, currentUrl.length-2)

 webView.setWebViewClient(object: WebViewClient() {

 override fun onLoadResource(WebView view, String url) {
 //call loadUrl() method  here 
 // also check if url contains partOfUrl, if not load it differently.
 if(url.contains(partOfUrl, true)) {
     //it should work if you reach inside this if scope.
 } else if(!(currentUrl.startWith("w", true))) {
     webView.loadurl("www.$currentUrl")

 } else if(!(currentUrl.startWith("h", true))) {
     webView.loadurl("https://$currentUrl")

 } else { 
   //...
 }
 }

 override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
  // you can call again loadUrl from here too if there is any error.
}
 // You should also override other override method for error such as
 // onReceiveError to see how all these methods are called one after another and how
// they behave while debugging with break point. 
} 
Simon.S.A.
  • 3,644
  • 5
  • 18
  • 30
SomeOne
  • 21
  • 2
0

For some web pages the key is to enable DOM storage:

webview.getSettings().setDomStorageEnabled(true);