How to Utilize Activity Methods in WebChromeClient

I am currently working on developing an Android application using Xamarin. One feature of the app involves a webview that needs to load upon the app's creation. Once the webview is fully loaded, I need to trigger some JavaScript code within the HTML page in order to set up a graph.

To achieve this, I have been attempting to utilize a custom WebChromeClient and override the OnProgressChanged method. When the webview finishes loading, I want it to call a specific method within my MainActivity.

This is what the code in my MainActivity looks like:

using System;
using System.Text;
using System.Timers;
using System.Collections;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Text;
using Android.Text.Style;
using Android.Webkit;

public class MainActivity : Activity
{
     WebView graph;

     protected override void OnCreate (Bundle bundle)
     {
          base.OnCreate (bundle);
          SetContentView (Resource.Layout.Main);

          graph = FindViewById<WebView>(Resource.Id.webGraph);

          //Initialize the WebView
          graph.SetWebChromeClient(new MyWebChromeClient()); 
          graph.Settings.JavaScriptEnabled = true;
          graph.LoadUrl("file:///android_asset/graph.html");

The custom MyWebChromeClient class I created is structured as follows:

class MyWebChromeClient : WebChromeClient
{
     public override void OnProgressChanged(WebView view, int newProgress)
     {
          base.OnProgressChanged(view, newProgress);

          if (newProgress == 100) {MainActivity.SetupGraph();}
     }
}

Despite having the SetupGraph method declared as public within the MainActivity, I am encountering difficulties accessing it. Any assistance with resolving this issue would be greatly appreciated!

Answer №1

To make a successful call to the setUpGraph() function in MainActivity, it is crucial to accept and store a reference of type MainActivity in the myWebChromeClient class.

EDIT

The myWebChromeClient class:

class myWebChromeClient : WebChromeClient
{
     public MainActivity activity;
     public override void OnProgressChanged(WebView view, int newProgress)
     {
          base.OnProgressChanged(view, newProgress);

          if (newProgress == 100) { activity.setUpGraph(); }
     }
}

And the activity:

    public class MainActivity : Activity
    {
         WebView graph;

         protected override void OnCreate (Bundle bundle)
         {
              base.OnCreate (bundle);
          SetContentView (Resource.Layout.Main);

          graph = FindViewById<WebView>(Resource.Id.webGraph);

          //Initializes the WebView
          myWebChromeClient client = new myWebChromeClient(); 
          client.activity = this;
          graph.SetWebChromeClient(client); 
          graph.Settings.JavaScriptEnabled = true;
          graph.LoadUrl("file:///android_asset/graph.html");

For simplicity's sake, I have included a public variable in the client. However, refrain from using the same in production. Instead, pass the reference in a constructor or use get-set methods.

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

Utilizing Angular and Express for routing with the seamless integration of html5mode

I'm facing an issue with making angular and express routing work together with html5mode enabled. When I change state from '/' to my admins state, everything works fine until I refresh the page. Then I only get a json result of admins but my ...

Stopping CSS animations at a specific point along the path without using timing functions can be achieved by implementing a targeted

Is there a way to pause an animation at the 50% mark for 2 seconds and then resume? P.S. The setInterval method is not recommended! function pauseAnimation() { document.getElementById("0").style.animationPlayState = "paused"; }; var pauseInterval = set ...

Is there a way to utilize a value from one column within a Datatables constructor for another column's operation?

In my Typescript constructor, I am working on constructing a datatable with properties like 'orderable', 'data' and 'name'. One thing I'm trying to figure out is how to control the visibility of one column based on the va ...

Open Chrome in fullscreen mode directly from your Android home screen without the statusbar displayed

One of my clients is looking to have a specific website launched from an icon on an Android tablet. Since he is leasing the tablets, we have full control over the hardware. The goal is for these tablets to exclusively display his site (which is a slideshow ...

What is the best way to uninstall the OneSignal library from my system entirely?

I am currently attempting to completely eliminate the OneSignal library from my project. I have removed its library from the dependencies list. This code snippet is from the Gradle app: plugins { id 'com.onesignal.androidsdk.onesignal-gradle-plugin& ...

Loop through the JSON data and display any empty strings

I encountered an issue while trying to convert an object string from a list of arrays using the JSON.parse method. Despite successfully converting the object string to an object, it appears empty when used within ng-repeat. Jade .item.col-md-4(ng-repeat= ...

Exploring Javascript's Timing Functions: SetInterval() and ClearInterval()

Hi there, I am currently working on developing an interval timer that allows users to set the number of rounds, working interval length, and resting interval duration. For instance, if a user inputs 30 seconds for work, 10 seconds for rest, and decides on ...

Trouble retrieving data from a JSON array with AngularJS ng-repeat and AJAX

I'm currently using Angular Js with ajax, but I'm having trouble retrieving output from a JSON array when using ng-repeat. When I try to display the data, all I see is [Object object] in the alert message. However, if I use $scope.names = respons ...

Tips for dividing a single row retrieved from a MySQL database that has been converted with json_encode so that it can be shown in

Looking to extract data from a MySQL query result in one PHP page and transfer it to a separate page with JavaScript. Here is my attempt so far: I am aiming to retrieve specific values from the selected row in the MySQL table and populate them into #event ...

Unable to locate the reference to 'Handlebars' in the code

I am currently attempting to implement handlebars in Typescript, but I encountered an error. /// <reference path="../../../jquery.d.ts" /> /// <reference path="../../../require.d.ts" /> My issue lies in referencing the handlebars definition f ...

What is causing SKMap to crash during map loading?

After attempting to integrate the Skobbler maps SDK into my android app, I encountered a crash whenever I tried to start the map. While reviewing the logs, everything seemed fine until a SIGSEGV signal with code SEGV_MAPERR appeared. 06-10 11:51:35.073: ...

Discovering the point of exit for a mouse from an image

Visit this website to see the effect in action: I am curious about how the image scrolls into and out of the direction where the mouse enters and leaves. Can you explain how this is achieved? ...

Encountering a surprise syntax error while trying to reference JavaScript from HTML?

After downloading this code from Github to make some modifications, I decided to run it locally. Link to the downloaded file The main index.html file references the JavaScript using: <script type="text/javascript" src="app.0ffbaba978f8a0c5e2d0.js">& ...

How can you iterate over the input elements that are currently visible within a form using Javascript?

Is there a way to clear the values of all visible input fields in a form using JavaScript? I'm currently struggling with setting text inputs to empty as they come out as undefined. Any suggestions on how to achieve this? ...

How can I retrieve information from a topic using kafka-node?

Having trouble reading data from a Kafka server? You may encounter an error message stating that the topic does not exist. Here are some questions to guide you: 1- How can I ensure that my Kafka connection is established? 2- What is the process for retri ...

Using the Vue.js Compositions API to handle multiple API requests with a promise when the component is mounted

I have a task that requires me to make requests to 4 different places in the onmounted function using the composition api. I want to send these requests simultaneously with promises for better performance. Can anyone guide me on how to achieve this effic ...

A guide on decoding a JSON response with a u' prefix in an Android environment

I am having trouble parsing a JSON response because all the fields have a u' prefix. I searched and realized it's in Unicode format, not UTF-8. How can I parse it correctly in Android? "{u'response': [{u'status': u'ONGOI ...

Tips for updating a field using Jquery

For my PHP + MYSQL + JQuery editing form, I am wondering how to display the updated data in the fields without refreshing the entire page after saving it to the database. Currently, I have this code snippet: $(document).ready(function (e) { $('f ...

Obtain your access token from auth0

Currently, my setup involves utilizing auth0 and nextJS. My objective is to have the user redirected to the callback API after successfully logging in with their credentials. Here is the snippet of code I am working with: import auth0 from '../. ...

Trouble with Bootstrap 5 hidden elements and jQuery fading in and out smoothly

Utilizing Bootstrap 5, I want to implement a fade in/out effect on a specific div element. jQuery offers a handy function called fadeToggle() for achieving this, so I decided to give it a try. The desired functionality is as follows: The div element star ...