DEV Community

Fernando Lucas
Fernando Lucas

Posted on • Updated on

Creating a Webview for Android Using Native Development with Java

Last week, at the company where I work, it was necessary to create an application for our platform using React. Initially, the idea was to convert this application to React Native, but I suggested creating a WebView app instead. It worked! Now, I'd like to share how to create a WebView for Android using native development with Java.

First of all, let's go over what you'll need:
Java installed on your machine, Android Studio, and all the required system variables (for Windows). Below, I'm providing all the useful docs:

Java - docs oracle
Android Studio - Android Studio docs

Once you have set up the development environment, let's create our app:

Open Android Studio and create an empty activity app. When your app is ready, clear everything in the activity_main.xml file. You might find a tag that displays a "Hello, World!" text on the screen. Remove it. After it, add the following code inside your androidx tag:

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

Enter fullscreen mode Exit fullscreen mode

It creates an WebView Element in our app, that is displayed in all screen. Now, with Java, we must catch this element and render our website in it.

put this code insed onCreate method in MainActivity.java:

webView = findViewById(R.id.webview);
webView.clearCache(true);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new MyWebViewClient());
String url = "your_website_without_/_in_the_end";
webView.loadUrl(url);
Enter fullscreen mode Exit fullscreen mode

Create a new private class to handle SSL errors:

private class MyWebViewClient extends WebViewClient {
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }
    }
Enter fullscreen mode Exit fullscreen mode

This code overrides the onReceivedSslError method to handle SSL errors and allow the WebView to proceed.

What this code do? Firsr, we catch the webview element webView = findViewById(R.id.webview);, and then, we clear the cache, enable JS, and set the client. Before, we just pass the URL and our webview is created.

to generate an APK:

Android Studio > Build > Build bundle(s) / APK(s) > Build APK(s)

Conclusion:
In this article, we learned how to create a WebView in Android using Java and Android Studio. By following these steps, you can easily display a website within your Android app using a WebView.

Note: Make sure to replace "your_website_without_trailing_slash" with the actual URL of the website you want to display in the WebView.

That's it! You now have a WebView app that can render web content in your Android application.

Top comments (0)