• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

webView | Native App | Open Website in Anderiod App |

irex

Lurker
Jul 11, 2019
2
1
Hi There

I am stuck at following piece of code.

when i write this piece of code
myWebView = (WebView)findViewById(R.id.WebView);
i get error "cannot resolve symbol 'webView'.

Please anyone can help me how to fix this error.
-------------------------
==for your reference i am copying MainActivity.Java code below ===

package com.irex.lingo_6;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {
private WebView myWebView;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myWebView = (WebView)findViewById(R.id.WebView);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://irex.pk/lingo-school/signin/index");
myWebView.setWebViewClient(new WebViewClient());
}

@override
public void onBackPressed() {
if(myWebView.canGoBack()) {
myWebView.goBack();
}else {
super.onBackPressed();
}

}
}
=====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:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp" />
</androidx.constraintlayout.widget.ConstraintLayout>

============ android manifest.xml====

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.irex.lingo_6">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
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/AppTheme">
<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>
 
There are many ways to write your webview code. Here is an example of how I do it.

This is a webview class complete with page load progressbar and the ability to download from any download links. You can also pass any url to it or as many as you like. If you only need one static url, then change the "static String url" with your static url.

Read the comments within the code as they explain what everything does.

Java:
package com.webviewexample;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.URLUtil;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

public class MyWebView extends AppCompatActivity {
    // Declare our web view.
    private WebView webview;

    // We can pass URLs from any other class to this string.
    static String url;

    // Optional progress bar for page loading progress.
    private ProgressBar progress;

    // A request code for our storage write request.
    private static final int WRITE_STORAGE = 1;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);

        // Optional progress bar for page loading progress.
        progress = findViewById(R.id.progressBar);

        // Attach our web view to our layout.
        webview = findViewById(R.id.webView);
        // Needed to interact with elements on most web pages.
        webview.getSettings().setJavaScriptEnabled(true);
        // This enables pinch to zoom.
        webview.getSettings().setBuiltInZoomControls(true);
        // Do not display the zoom controls on the screen.
        webview.getSettings().setDisplayZoomControls(false);
        // Loads a page to fit in the screen (zoomed out).
        webview.getSettings().setLoadWithOverviewMode(true);
        // Do not constrain the viewport to the web view dimensions.
        webview.getSettings().setUseWideViewPort(true);
        // Attach our web view to our WebViewClient.
        webview.setWebViewClient(new MyWebViewClient());
        // We call our url string variable to load.
        webview.loadUrl(url);

        // Adds a DownloadListener to our web view. This allows us to click on
        // download links and have items download to our downloads directory.
        webview.setDownloadListener(new DownloadListener() {
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype);
                String cookie = CookieManager.getInstance().getCookie(url);
                DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
                request.setAllowedOverRoaming(false);
                request.allowScanningByMediaScanner();
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
                request.addRequestHeader("Cookie", cookie);
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                // Check for storage write permission before attempting to download.
                if (getPermission()) {
                    dm.enqueue(request);
                }
            }
        });

    }

    // Check if storage write permission has been granted. If not, request it.
    private boolean getPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                // True if permission granted exists.
                return true;
            } else {
                // We ask for storage write permission if it doesn't exist.
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_STORAGE);
                return false;
            }
        } else {
            // True for SDK < 23
            return true;
        }
    }

    // Check if user granted or denied storage write permission when requested and
    // run code for either situation. This method is optional, but useful.
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case WRITE_STORAGE: {
                if (grantResults.length > 0 &amp;&amp; grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(getApplicationContext(), "Permission Granted!", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(), "Permission Denied!", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    // Attach our web view to our WebViewClient.
    private class MyWebViewClient extends WebViewClient {
        // This method makes sure that any links we click will open within
        // our app instead of launching in the default web browser.
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }

        // Since this method is called every time a new page starts to load, it's
        // perfect to run our Progress Bar.
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            progress.setVisibility(View.VISIBLE);
            super.onPageStarted(view, url, favicon);
        }

        // Called whenever a page has finished loading. Here we can end our
        // page loading progress bar and take it out of view.
        @Override
        public void onPageFinished(WebView view, String url) {
            progress.setVisibility(View.GONE);
            super.onPageFinished(view, url);
        }

    }

    // If we have clicked through multiple pages, this allows the back button
    // to take us back through each page.
    @Override
    public void onBackPressed() {
        if (webview.canGoBack()) {
            webview.goBack();
        } else {
            super.onBackPressed();
        }
    }
}

You can then pass a url to this class from any other class like this...

Java:
public void googleButton(View view) {
    MyWebView.url = "https://www.google.com/";
    Intent intent = new Intent(this, MyWebView.class);
    startActivity(intent);
}

I wrote a full tutorial complete with source code on github and a fully working app in the following link...
https://intechgeek.com/android-webview/

Try the sample app I provided to see if this code serves your purpose. Just check the app/release/ folder in the github source code.
 
Upvote 0
First, that error would tend to indicate that you haven't imported WebView. @GameTheory's example shows that (line 16)

Also, your WebView doesn't have an ID, and you're trying to use an id to get it
Code:
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp" />

If you want to use ID, you'll need to add one, like
Code:
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp" />
and be sure to use the id exactly as defined.

Follow that link @GameTheory shared, it looks like it will give you a good start.
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones