Executing a Java function when a user clicks a button using

I have a situation where I am creating an HTML button using JavaScript and injecting it through Java. The goal is for this button to change activity when clicked. Below is the code snippet:

public class WebsiteActivity extends AppCompatActivity implements View.OnClickListener {
Button btnActTwo;
//...

private class WebAppInterface {
    Context mContext;

    WebAppInterface(Context c) {
        mContext = c;
    }

    @JavascriptInterface
    public void clickBtnActTwo() {
        btnActTwo = (Button) findViewById(R.id.btnActTwo);
        btnActTwo.setOnClickListener(WebsiteActivity.this);
        Log.e("TEST","TEST");
    }
//...

public void onPageFinished(WebView view, String url) {
            String javascript = "javascript:"
                    + "function onClickBtnActTwo() {Android.clickBtnActTwo();}"
                    + "var btnacttwo = document.createElement('div');"
                    + "btnacttwo.innerHTML = 'BtnAcTwo text';"
                    + "btnacttwo.onclick = onClickBtnActTwo;"
                    + "element = document.getElementsByClassName('contentMenu')[0];"
                    + "element.appendChild(btnacttwo);"
            view.loadUrl(javascript);
//...

@Override
public void onClick(View v) {

    switch (v.getId()) {
        case R.id.btnActTwo:
            Log.e("TEST2","TEST2");
            Intent btnActTwoIntent = new Intent(this, BtnActTwoActivity.class);
            startActivity(btnActTwoIntent);
            break;
//...

When testing, the console displays the TEST tag when pushing the dynamically created div button, but not TEST2. It seems like there might be an issue with implementing the functionality from injected JavaScript. Any suggestions on how to make this work seamlessly?

Answer №1

I managed to figure it out on my own by directly using Intent. Perhaps this solution can be helpful for someone else in the same situation.

private class WebAppInterface {
    Context mContext;
    WebAppInterface(Context c) {
        mContext = c;
    }
    @JavascriptInterface
    public void clickBtnActTwo() {
        //...
        Intent myIntent = new Intent(mContext, AdsActivity.class);
        startActivity(myIntent);
    }

However, I'm still puzzled about what went wrong with my setOnClickListener implementation.

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

Is there a way to efficiently include numerous jQuery scripts in a batch process, each with a slight variation, using a loop?

Currently, I have a script that calculates the blur effect for multiple images based on the mouse position and scroll position. However, I am looking for a more efficient way to apply this to around 100 images without duplicating the script each time. var ...

Supertest request not being processed by Express POST API Route

Trying out a test on an Express API POST Route that employs Express Validator for check: usersRouter.post( '/', [ check('name', 'Need to input a name.').not().isEmpty(), check('email', 'Must add a va ...

Struggling with PHP variables and AJAX JavaScript

Hey everyone, I've made some edits and have a new question regarding a similar issue. On test.php in my Apache server, I have a PHP script that connects to a database and retrieves data from a table. <?php $con = mysqli_connect("localhost", "user" ...

Combining arrays of properties in two objects

Below are the JavaScript objects I am working with: Object A: 0300 : ["295", "293", "298"], 0800 : ["293", "298"], 0930 : ["295"], 1130 : ["297", "293", "298"], 1230 : ["295"] Object B: 0300 : ["297"], 0800 : ["297"], 0930 : ["293"], I aim to merge th ...

AngularJs: Tips for running functions synchronously

Is there a way to ensure that three services are executed synchronously in AngularJS? I'm facing an issue where my logic fails because the $http.get() services are running asynchronously. The goal is to read JSON fields from each service response, set ...

Retrieve data from an HTML form and utilize it to search a JSON array for a specific value

If I have a Json File structured like this: {"403": [ { "403-01-01": "219,00" }, { "403-01-02": "180,00" } ], "404": [ { "404-01-01": "26,00" }, {"403-01-02": " ...

Struggling to maintain context with axios in React despite diligent use of arrow functions

In my component, I have a function for posting data. Although it works well, the context of my component is lost in the success message. This is puzzling because I am using arrow functions. Why does the "this" context get lost in this situation? The issu ...

Steps for making a Trello card via a Discord bot

As a beginner in Java script coding, I am attempting to create a bot for adding a card to my Trello board. Despite hours of searching online, I have not been able to find a solution. if(isCommand('gameban', message)){ if(!message.membe ...

Enhance your property by adding the isDirty feature

Managing changes to properties of classes in TypeScript can be optimized by tracking only the fields that have actually changed. Instead of using an array to keep track of property changes, I am exploring the idea of implementing an isDirty check. By incor ...

Tips for using jQuery to identify the most recently modified row in an HTML table

Is there a way to identify the most recently modified (either newly added or changed) row in an HTML table? ...

Animation that slides in from the left using CSS styling

My current project involves creating a slideshow, and while it is mostly working fine, I am facing an issue with the animations. The animation for sliding out works perfectly, but the animation for sliding in from the left doesn't seem to be functioni ...

Delving deeper into the features of Telerik Platform

We are transitioning from .NET development and are currently exploring how to make use of the Telerik Platform in a Cordova environment, specifically for JavaScript. The code seems to be a possible model for managing activities. However, we're unsure ...

Displaying nested JSON data in a user interface using React

I have a complex nested JSON structure that I am using to build a user interface. While I have successfully implemented the first part, I am encountering difficulties with the second part. My Objective The nested JSON displays parent elements and now I a ...

Retrieving data from an XML node

I am completely new to XML parsing. My current task involves reading an XML file from a shared drive on my computer and transferring it to another shared drive. Here is the XML file that I am working with, and specifically, I am attempting to extract the v ...

Unable to receive data in an array with Vuejs

Here is the code snippet I am working with: let data = res.data.data; console.log('data: ', data) const list = []; for(let i = 0; i < data.length; i++){ console.log('data i: ', data[i]) //this line is not being printed in the ...

How can I extract the value of a JavaScript variable using jsoup in an HTML document?

<html> <script type="text/javascript"> var map = null; jQuery(function($) { L.marker([50.065407, 19.945104], {title: 'Cat'}) .bindPopup('<h3>Cat</h3> ...

Reducing HTML content to 20 words efficiently through the use of JS and VueJS

Currently in the process of developing a news feed using VueJS and have encountered an issue with rendering the content. Unfortunately, the API I am working with does not allow for easy customization to fit my specific needs. This API provides all the cont ...

Is it possible for the number returned by setTimeout() in JavaScript to be negative?

Is it possible for a number returned by the setTimeout() function in JavaScript to be negative? Currently, I've observed that the timeoutIds generated are sequentially numbered in Chrome as 1,2,3,4,5,6... While in Firefox, they start from number 4 an ...

"Employing the ScrollSpy feature in Bootstrap allows you to effortlessly monitor

Recently, I came across a document containing Bootstrap 4 code like the following: <div className="container"> <nav class="navbar navbar-expand-lg navbar-light"> <a class="navbar-brand active" aria-current="true" href="/"> ...

What is the best way to merge three or more Observables together?

I have obtained 3 different Observables from 3 separate Services through API calls: this.gs.getLocationName().subscribe((loc) => this.locationName = loc); this.gs.getLocationInfo(this.locationName).subscribe((data) => { this.lat = data.results.ge ...