How to load external webpage inside WebView

Gilbou picture Gilbou · Sep 5, 2011 · Viewed 262.9k times · Source

My problem is that the webpage is not loaded inside the webview.

mWebview.loadUrl("http://www.google.com"); launches the web browser...

This is the code of my activity:

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class Main extends Activity {

    private WebView mWebview;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mWebview = new WebView(this);
        mWebview.loadUrl("http://www.google.com");
        setContentView(mWebview);
    }   
}

I added the required permission in the Manifest:

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

Answer

Gilbou picture Gilbou · Sep 5, 2011

Thanks to this post, I finally found the solution. Here is the code:

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import android.annotation.TargetApi;

public class Main extends Activity {

    private WebView mWebview ;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        mWebview  = new WebView(this);

        mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript

        final Activity activity = this;

        mWebview.setWebViewClient(new WebViewClient() {
            @SuppressWarnings("deprecation")
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
            }
            @TargetApi(android.os.Build.VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
                // Redirect to deprecated method, so you can use it in all SDK versions
                onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
            }
        });

        mWebview .loadUrl("http://www.google.com");
        setContentView(mWebview );

    }

}