Tips for LoadingUrl in WebView from a Different Class on Android App

I am a beginner in Android app development and Java. I want my app to use a WebView to display its content. The user should be able to interact with HTML elements, such as buttons or links, which will then send requests to my Android Java class to navigate to different pages.

To achieve this, my main class loads the WebView using the following code:

WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
myWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("file:///android_asset/html/status01.html");

Inside the public class JavaScriptInterface, I would like to create a function that loads another URL:

public void showOffers() {
    WebView myWebView = (WebView) ((Activity) mContext).findViewById(R.id.webview);
    myWebView.loadUrl("file:///android_asset/html/offers.html");
}

However, I encounter an error stating:

Activity cannot be resolved to a type

How can I access the WebView from my JavaScriptInterface class in order to load another URL?

Answer №1

Declare the class JavaScriptInterface as an inner class within your Activity and save the reference to the WebView as a member variable of your Activity.

Since inner classes have access to the member variables of the class they are defined in, you can modify your code like this:

MyWebActivity extends Activity{
    private WebView myWebView;
    protected void onCreate(Bundle bundle){
        myWebView = (WebView) findViewById(R.id.webview);
        myWebView.addJavascriptInterface(new JavaScriptInterface(), "Android");
        myWebView.setWebViewClient(new WebViewClient());
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        myWebView.loadUrl("file:///android_asset/html/status01.html");
    }

    private class JavaScriptInterface{
        JavaScriptInterface(){
        }
        public void showOffers() {                
            myWebView.loadUrl("file:///android_asset/html/offers.html");
        }
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating Comet applications without the need for IFrames

Currently embarking on my journey to develop an AJAX application with server side push. My choice of tools includes Grizzly Comet on Glassfish V2. While exploring sample applications, I've noticed that most utilize IFrames for content updates on the c ...

A guide on harnessing the power of the fetch API to retrieve data from an external

In the process of developing a fetchBill function, I have assigned the URL https://randomapi.com/api/006b08a801d82d0c9824dcfdfdfa3b3 to a variable named api. This function utilizes the browser's fetch function to send an HTTP request to the specified ...

issue encountered when implementing slick.js in angular 6

Trying to implement slick.js, a carousel framework, in an Angular project. Initially attempted 'npm install slick --save' and manually adding the downloaded files to scripts and styles JSON objects. When that failed, resorted to importing the C ...

Error in Java: Unable to convert "void" to type double

I've been facing an issue while trying to assign a value from an SQL database to a double within a void method. The error "Cannot convert from void to double" keeps popping up. I've searched through various resources but haven't found a solu ...

The JSON StackOverflowError occurs when there is a parent-child relationship between two objects

While attempting to establish a parent-child relationship between various objects, I encountered a challenge. In my scenario, I am aiming to organize objects within other objects (for example, a container holding multiple items or other containers with it ...

Is there a maximum number of window.open() calls that can be made in JavaScript?

Can the use of window.open("URL"); in JavaScript be limited? Upon attempting to open three windows using window.open("URL"), the third window did not open separately. Instead, it refreshed the contents of the first window and displayed the contents of ...

Using JavaScript, post an image to imgur (API version 3) from a canvas

Currently, I am working on an amusing Chrome experiment called the Mustache Mirror! If you're interested, you can check it out here. I am aiming to incorporate the Imgur API V3 for uploading an image from the canvas to Imgur and displaying the link. U ...

What is the best way to limit the number of items displayed in a Bootstrap card?

While using bootstrap cards to display content, I encountered an issue when integrating it with the backend for looping. The items were continuously added to the right side instead of being set in columns of 3 and continuing straight down. It should look ...

Single-use binding format

I am a beginner with Angular and I have some doubts about the syntax used in Angular. In AngularJS, we can achieve one-time binding like this: <p>{{::myVar}}</p> In Angular, I know we can do it differently. <p [innerText]="myVar"></ ...

Design a customizable overlay with a moveable and size-adjustable layer below it

After working with kineticjs, I successfully created an app that allows images to be draggable and resizable, which is great progress; Now, I am facing a challenge: I want to have an overlay in the center with a block of variable height/width that display ...

Incorporating Fontello spinner icons into CSS styling

Currently, I have a background image set in the CSS and I am looking to replace it with a Fontello spinner image class. How can I achieve this? #divOverLay.show { background-color: rgba(0, 0, 0, 0.0); background-image: url('../images/spinner_ ...

AJAX: Send a value, perform a query based on this value, and retrieve a JSON array

Can anyone explain why this code isn't functioning properly? I am attempting to submit a value from a form to a PHP file that performs a select query in my database using that value. The goal is to return a JSON array to Ajax and display all the resul ...

Neighbor cell UMTS identifiers

When utilizing the code snippet provided below, I am encountering a problem where I only receive cell id's in 2G mode. In instances where I switch to 3G mode, I sometimes get -1 for HSDPA or no value for UMTS. The source code is as follows: for (int ...

populate a data list with information sourced in Angular 8

I am looking to populate this model oldDataSource: Array<any> = []; with the values from the datasource. This is the code I have tried: ngOnInit(): void { this.dataSourceInit(); } dataSourceInit(): void { this.dataSource = new DefaultScore ...

GraphQL Shield throws an 'Unauthorized' error for a permitted mutation

I've been working on setting up a GraphQL API with apollo-server-express, and I'm trying to handle permissions using graphql-shield middleware. However, I'm running into some issues when it comes to allowing mutations to be executed. My aim ...

Shared variables in Node.js allow for multiple users to access different entry points simultaneously

In the process of transitioning my node-js application from a single-tenant database to a multi-tenant database, I am facing some challenges. The application code is accessed through an express api and various services are run through different entrypoints ...

Transitioning images with jQuery

For my college project website that focuses on selling music, I have implemented a buy button that resembles the one seen on Apple's app store. You can view the images of the button here: View Image 1 View Image 2 I am wondering if anyone is famili ...

how to check if a string has white spaces in a react application

If the input string has white space, the alert will indicate unsuccessful. If the input string does not have any white space, the alert will be successful. import React from "react"; export default function DropDown() { let i = document.getEle ...

Constructing Kiwi Browser to cater to legacy Android editions

Discover a unique variant of the Chromium browser known as Kiwi, which can be downloaded on Android devices through the Google Play Store. As of August 2021, it is only compatible with Android 5.0 and above, whereas previously it supported Android 4.1 and ...

Enhancing a Dropdown List with Jquery Using JSON Data

I am trying to populate a list using a JSON collection of objects. Here is the method that my action is returning: public ActionResult GetProductCategories() { var categories = _entities.ProductCategories.ToList(); var res ...