133

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" />
live-love
  • 34,372
  • 16
  • 163
  • 152
Gilbou
  • 5,134
  • 5
  • 22
  • 27

14 Answers14

229

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 );

    }

}
devgun
  • 924
  • 12
  • 31
Gilbou
  • 5,134
  • 5
  • 22
  • 27
  • Nice thing but i want to Display the web contain page wise.it`s possible using webview? – Zala Janaksinh Aug 16 '12 at 06:37
  • 16
    Dont forget to add Permission – star18bit Jun 05 '13 at 05:38
  • 2
    Actually, in order to handle with the url inside your webview you should set a webviewclient, if you do not set a client, default behaviour is to launch an application that handles URLs. See [this link](http://developer.android.com/guide/webapps/webview.html#HandlingNavigation) – erdemlal Nov 22 '13 at 15:59
  • 2
    Enabling java script opens up your app to potential security issues and I am sure android sdk warns you against it when you use it in code. Don't do this unless you can control which websites you display in your webview and enabling java script should not be seen as an easy solution. – LostPuppy Jun 13 '14 at 22:41
  • Shouldn't that `onReceivedError` be an `@Override`? – Adrian Seeley Jan 21 '15 at 20:40
  • Actually the only line required is `mWebview.setWebViewClient(new WebViewClient());` – Sébastien Feb 06 '17 at 11:53
  • 1
    Not opening this code.. Showing `Webpage not available` – Ranjith Kumar Nov 19 '19 at 12:04
  • @RanjithKumar Works for me, but I had to comment out `setContentView(mWebview );` from the end , because it was giving a different error: [The specified child already has a parent. You must call removeView() on the child's parent first](https://stackoverflow.com/questions/28071349/the-specified-child-already-has-a-parent-you-must-call-removeview-on-the-chil) – gregn3 Apr 05 '20 at 22:00
47

try this

webviewlayout.xml:

<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
         android:id="@+id/help_webview"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"
         android:scrollbars="none"
/>

In your Activity:

WebView webView;
setContentView(R.layout.webviewlayout);
webView = (WebView)findViewById(R.id.help_webview);
webView.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://www.google.com");

Update

Add webView.setWebViewClient(new WebViewController()); to your Activity.

WebViewController class:

public class WebViewController extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}
Bryan Herbst
  • 62,910
  • 10
  • 119
  • 113
Farhana Haque
  • 1,361
  • 13
  • 22
  • 1
    sorry. seems I changed something in the manifest and now it works too. but still, the page is loaded in the web browser, not in the webview. – Gilbou Sep 05 '11 at 09:03
  • this line worked for me: webView.getSettings().setJavaScriptEnabled(true); – pixparker Sep 04 '14 at 17:06
  • 1
    mWebview.getSettings().setJavaScriptEnabled(true); worked for me, we have to add this line – neena Aug 18 '16 at 10:49
  • This is a bad way of doing it. `shouldOverrideUrlLoading` is called for all pages loaded in the webview. This includes iFrames, meaning that if the page loads an iFrame, the page will be replaced by the iFrame. This is discouraged on the relevant android docs page. – Hack5 Jan 13 '18 at 08:18
19
public class WebViewController extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}
webView.setWebViewClient(new WebViewController());
Rahul
  • 852
  • 9
  • 14
  • 1
    I am setting a custom webViewClient to my webview. In my custom made WebViewClient, I have overloaded the shouldOverrideUrlLoading method to load my url. I am passing my url with this loc: webview.loadUrl("URL"); – Rahul Aug 28 '13 at 09:57
  • This is a bad way of doing it. `shouldOverrideUrlLoading` is called for all pages loaded in the webview. This includes iFrames, meaning that if the page loads an iFrame, the page will be replaced by the iFrame. This is discouraged on the relevant android docs page. – Hack5 Jan 13 '18 at 08:19
13

Please use this code:-

Main.Xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:background="@drawable/background">
    <RelativeLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:background="@drawable/top_heading"
        android:id="@+id/rlayout1">
        <TextView android:layout_width="wrap_content"
            android:layout_centerVertical="true" android:layout_centerHorizontal="true"
            android:textColor="#ffffff" android:textSize="22dip"
            android:textStyle="bold" android:layout_height="wrap_content"
            android:text="More Information" android:id="@+id/txtviewfbdisplaytitle" />
    </RelativeLayout>
    <RelativeLayout android:layout_width="fill_parent"
        android:layout_height="fill_parent" android:layout_below="@+id/rlayout1"
        android:id="@+id/rlayout2">
        <WebView android:id="@+id/webview1" android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1.0" />
    </RelativeLayout>
</RelativeLayout>

MainActivity.Java

public class MainActivity extends Activity {
    private class MyWebViewClient extends WebViewClient {
          @Override
          public boolean shouldOverrideUrlLoading(WebView view, String url) {
              view.loadUrl(url);
              return true;
          }
    }
    Button btnBack;
    WebView webview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        webview=(WebView)findViewById(R.id.webview1);
        webview.setWebViewClient(new MyWebViewClient());
        openURL();
    }

     /** Opens the URL in a browser */
    private void openURL() {
        webview.loadUrl("http://www.google.com");
        webview.requestFocus();
    }
}

Try this code if any query ask me.

Rahul Patil
  • 2,629
  • 2
  • 18
  • 32
Dipak Keshariya
  • 21,618
  • 18
  • 74
  • 127
  • 1
    it works. But you missed 2 things. First, you did not show internet permission is needed, Second, use of background image. thanks – Sumon Bappi Oct 17 '15 at 09:10
6

It's very simple try integrate these lines of code first take permission in the Android Manifest file

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

then write some code in you Activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.MainActivity">

<WebView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/help_webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

/>

</LinearLayout>

Then write these code in your MainActivity.java

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class MainActivity extends Activity{
    private WebView mWebview ;
    String link = "";// global variable
    Resources res;// global variable
    @Override


      protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            setContentView(R.layout.activity_modernherbal_main);
            mWebview  = (WebView) findViewById(R.id.help_webview);
            WebSettings webSettings = mWebview.getSettings();
            webSettings.setJavaScriptEnabled(true);
            webSettings.setUseWideViewPort(true);
            webSettings.setLoadWithOverviewMode(true);



        final Activity activity = this;

        mWebview.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
            }


});

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

}

}

Try this it'll help you to solve your problem

Pronab Roy
  • 828
  • 1
  • 12
  • 18
4

just go into XML file and give id to your webView then in java paste these line:

   public class Main extends Activity {

private WebView mWebview;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.Your_layout_file_name);

    mWebview = (WebView)findViewById(R.id.id_you_gave _to_your_wenview_in_xml);
    mWebview.loadUrl("http://www.google.com");
    }   
}
Ankush Rawat
  • 189
  • 10
2

I used this code that was cool. but have an error. " neterr_cleartext_not_permitted" show when you use this code then you will face this problem..

I got a solution of this.you have to add this in your AndroidManifest.xml near about Application

android:usesCleartextTraffic="true"
<uses-permission android:name="android.permission.INTERNET" /> // ignore if you already added. outside of Application.
pankaj kumar
  • 698
  • 5
  • 18
1

You can do like this.

webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("Your URL goes here");
KarthikKPN
  • 625
  • 10
  • 21
1

try this;

webView.loadData("<iframe src='http://www.google.com' style='border: 0; width: 100%; height: 100%'></iframe>", "text/html; charset=utf-8", "UTF-8");
alicanozkara
  • 3,945
  • 1
  • 21
  • 22
1

Add Internet permission in AndroidManifest.xml

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

In your Layout:

<?xml version="1.0" encoding="utf-8"?>
<WebView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/webView"
 />

In your Activity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try {
        progressDialog = new ProgressDialog(this);
        url_Api = "https://docs.microsoft.com/en-us/learn";

        webView = this.findViewById(R.id.webView);

            progressDialog.setMessage(getString(R.string.connection_Wait));
            progressDialog.setIndeterminate(false);
            progressDialog.setCancelable(true);
            progressDialog.show();

            LoadUrlWebView( url_Api );
    }catch (Exception e){
        Log.w(TAG, "onCreate", e);
    }
}

private void LoadUrlWebView( String url_api ) {
    try {
        webView.setWebViewClient(new WebViewClient());
        webView.setWebChromeClient(new MyWebChromeClient( url_api ));
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setAllowContentAccess(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDisplayZoomControls(false);

        webView.loadUrl(url_api);
    } catch (Exception e) {
        Log.w(TAG, "setUpNavigationView", e);
    }
}

private class MyWebChromeClient extends WebChromeClient {
    private String urlAccount;

    public MyWebChromeClient( String urlAccount ) {
        this.urlAccount = urlAccount;
    }

    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        try {
            //Tools.LogCat(context, "INSIDE MyWebChromeClient | onProgressChanged / newProgress1:" + newProgress);
            progressDialog.setMessage(newProgress + "% " + getString(R.string.connection_Wait));
            if (newProgress < 100 && !progressDialog.isShowing()) {
                if (progressDialog != null)
                    progressDialog.show();
            }
            if (newProgress == 100) {
                if (progressDialog != null)
                    progressDialog.dismiss();
            }
        }catch (Exception e){
            Log.w( "onProgressChanged", e);
        }
    }

    @Override
    public void onReceivedTitle(WebView view, String title) {
        super.onReceivedTitle(view, title);

        sharedPreferences = new Shared_Preferences( context );
        sharedPreferences.setPageWebView(view.getUrl());
    }

}
Amar Ilindra
  • 668
  • 1
  • 9
  • 21
Grafritz Design
  • 151
  • 1
  • 4
  • 1
    Kindly use English, as this is an English only site. In this case it's only 3 lines that needs translating. – Scratte Feb 26 '20 at 01:11
1

Add WebView Client

mWebView.setWebViewClient(new WebViewClient());
SamiunNafis
  • 101
  • 2
  • 5
0

You need to add WebView client

mWebView.setWebViewClient(new WebViewClient() {

   public void onPageFinished(WebView view, String url) {
        // do your stuff here
    }
});

also you can use onPageFinished to do task after webview done loading web page

Mirza Ahmed Baig
  • 2,931
  • 1
  • 16
  • 33
0

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <WebView
        android:id="@+id/webView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java:

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {
    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }
    WebView webView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = findViewById(R.id.webView);
        webView .loadUrl("http://www.google.com");
        webView.setWebViewClient(new MyWebViewClient());
    }
}

AndroidManifest.xml: (add uses-permission and android:usesCleartextTraffic)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

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

    <application
        android:usesCleartextTraffic="true"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApplication">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
live-love
  • 34,372
  • 16
  • 163
  • 152
-1

Add below method in your activity class.Here browser is nothing but your webview object.

Now you can view web contain page wise easily.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && browser.canGoBack()) {
        browser.goBack();
        return true;
    }
    return false;
}
  • This adds a functionality to the "back" button at the bottom of the Android phone: It works as a "back" browser button. – Don Larynx Mar 11 '15 at 20:30