Transferring callback functions from JavaScript to Java in Android

As I work on developing an Android app using HTML5/JavaScript, I've encountered some limitations. One challenge I face is calling a function implemented in Java code from within JavaScript, specifically to create a particular type of dialog. While the process seems straightforward, there are nuances involved:

public class MyClass () {
    // other stuff

    public void createMyDialog (/* arguments */) {
        DialogBuilder builder = ...
        builder.setItems(myItems, new DialogInterface.OnClickListener () {
            @Override
            public void OnClick (DialogInterface dialog, int which) {
                droidGap.loadUrl(/* what now? */);
            }
        });
    }
}

To expose this class to JavaScript, the following steps can be followed:

MyClass myClass = new MyClass();
appView.addJavascriptInterface(myClass, "myClass");

Although this setup allows for access to window.myClass.createMyDialog() from JavaScript, I desire to include a callback function that would receive the which variable as an argument. This requires modifying the method signature to:

public void createMyDialog (final String callback)

and invoking it with something like

window.myClass.createMyDialog(
    function (which) {
        alert(which);
    }
);

I have managed to make this work by passing the function as a string and then executing

appView.loadUrl("javascript:(" + callback + ")(" + which + ");");
in Java. However, this approach feels less than ideal and has a notable drawback – which brings me to my main concern. When calling createMyDialog from JavaScript within a class context, such as:

function myJSClass () {
    this.myVar = -1;

    this.myFunc = function () {
        window.myClass.createMyDialog(
            function (which) {
                this.myVar = which;
            }
        );
    }
}

var myObj = new myJSClass();
myObj.myFunc();

The issue arises when trying to reference this, which ends up pointing to window instead of the intended class instance due to the call originating from Java. Various solutions like storing var _this = this or utilizing bind have not proven effective in preserving the correct context. I am aware that frameworks like PhoneGap offer functionalities similar to what I'm attempting with navigator.notification.confirm. So, what would be the recommended approach in this scenario?

Your insights are greatly appreciated!

Answer №1

To begin, it is highly recommended that you create a Plugin for your project. We've encountered various issues with Java/JS and JS/Java integration, so utilizing our tried-and-tested code will save you time and headaches.

Next, ensure that your dialog runs on the UI thread to prevent any potential problems from arising.

Lastly, if you need to trigger specific success or error callbacks from Java based on dialog actions, you can achieve this using the PluginResult class. Setting the appropriate condition will invoke the corresponding callback method.

For further guidance, take a look at the PG code for notifications, which offers examples showcasing different types of dialogs:

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

Develop a simple scheduling application in Java that allows users to manage their events, as well as receive notifications for upcoming events for the current week or day,

Originally, I had hoped to create this simple program without seeking assistance from others and taking up their valuable time. However, I have hit a roadblock with my "ideas" at this point. Up until now, Google has been my guide, but unfortunately, it can ...

The server gets blocked by numerous AJAX GET requests happening at the same time until the data gets returned

In my Rails application, I am using the gridList library to display charts. The chart data is fetched asynchronously from a controller method in JSON format via AJAX. Upon initial page load, each gridlist item displays a loading icon while simultaneously m ...

I am looking to update my dexie values from null to empty strings

I am facing an issue where the data-table values with null entries need to be replaced with empty strings. There are instances when the department value is empty, resulting in null entries in the data tables. db = db_open(); db.fuel.toArray().then(fuel = ...

Trouble with escaping characters in Javascript?

My code looks like this: `message.channel.send( const Discord = require('discord.js'); const client = new Discord.Client(); const token = 'your bot token here'; client.on('ready', () => { console.log('I am ready!& ...

When trying to import the Editor from draft-js-plugins-editor in a blank project, it results in TypeErrors

I recently started a new React project in Webstorm and added draft-js, draft-js-plugins-editor, draft-js-hashtag-plugin, and draft-js-mathjax-plugin using node modules. Following the instructions provided in the 'getting started' section on thei ...

Sorting through an array of dates in milliseconds, extracting objects with subcategories, and dynamically displaying them on the calendar based on the specific date

So I am currently working with a JSON object containing an array of objects structured like this: [ { "id": 0, "name": "Sophia Mason", "availability": [ { "date": 1522216800000, "times": ["9:00 am", "2:3 ...

Guide on how to "attach" the routes of an Angular 2 module to a specific location within the routing structure

Let's consider a scenario where the main routing module is defined as follows: // app-routing.module.ts const appRoutes: Routes = [ { path: 'login', component: LoginComponent }, { path: 'auth', ...

Utilize the click spinner feature on a single button in Angular

I have a table with a list of items and each item has a button to request a PDF document from the server. I want to show a spinner while waiting for the document to be received. Currently, when I click on a button, the spinner appears on all buttons instea ...

Verifying in PHP if the request is intended for a JavaScript worker

After doing my research on MDN for the referrer-policy, as well as searching through Google, DuckDuckGo and Stack Overflow, I still find myself stuck on a seemingly simple yet elusive issue. Journey of Data the browser sends a request to the server the ...

A guide on utilizing the index column for multiple tables using just one statement in the datatable js library

I've incorporated the datatable js for managing two tables on a single page. HTML <!-- Table#1 --> <table class="dataTable"> <thead> <tr> <td>#</td> <td>col1</td> </tr> &l ...

How is it determined in the Java bytecode/class format whether a method overrides another?

Is it possible for a method in a subclass to override a method in its superclass when they have the same name, parameter types, and a return type that is a subtype of the return type of the superclass method? This question arises from observations in the ...

Having trouble with Material-UI Textfield losing focus after re-rendering? Need a solution?

I am currently utilizing Material-ui Textfield to display a repeatable array object: const [sections, setSections] = useState([ { Title: "Introduction", Text: "" }, { Title: "Relationship", ...

Error Encountered While Building Android APK. A Puzzling Error Has Ar

What is the reason for this error showing up in the console when building an Android application project? I am encountering a "UNEXPECTED TOP-LEVEL EXCEPTION: java.lang.NullPointerException" error specifically during the build process of one project, whi ...

Differences between urlencoded and form-data in Node.js

Can anyone suggest a fast method to distinguish between passing urlencoded data and form-data (multiparty) data in Node.JS? ...

Encountering a 400 error in Firebase Cloud Messaging due to missing the "to" parameter

I am currently experimenting with sending a downstream push notification from an Android client for practice purposes only. When using the following code: private void send() { String urlString = "https://fcm.googleapis.com/fcm/send"; JSONObject ...

Retrieve data from a Rails controller using Ajax

Seeking assistance and insight for a coding dilemma I'm facing. In my Rails application, I have a controller named get_songs that retrieves a hash of songs belonging to the currently logged-in user. What I'm trying to achieve is to fetch this dat ...

Guide to obtaining a drawable resource in android using Java

I am currently working on an android application and I am trying to figure out how to properly reference a drawable in my Java code. The image or drawable is located in the drawable folder and is already being referenced in my XML file. How can I access it ...

Is there a method to display a loading animation while the micro apps are being loaded in a single spa project?

Currently, I am working on a project using single spa and I need to implement a loader while my micro app is being loaded. Additionally, I also need the loader to be displayed when switching between these micro apps. Are there any methods to accomplish t ...

Android O encountered an issue while trying to activate the AutoFill Service through an Intent

When I tried to enable the AutoFill Service using this code: Intent dialogIntent = new Intent(Settings.ACTION_REQUEST_SET_AUTOFILL_SERVICE); startActivity(dialogIntent); I encountered the following exception: FATAL EXCEPTION: main Process: com. ...

A step-by-step guide on how to refresh a circular loading indicator

I have been researching how to create a circular progress bar using canvas, and I came across this code. After making some modifications to the code snippets that I found online, I encountered an issue - I can't seem to reload the circular path once i ...