Executing a JavaScript function in an Android controller using Java

Currently, I am in the process of developing a hybrid Android application that incorporates Cordova, Ionic, and Angular. As part of this project, I am working on implementing barcode scanning functionality using native Java code. While I have successfully managed to call Java methods from JavaScript using JavaScriptInterface, I am encountering difficulty passing the return value from the Java method back to JavaScript. Can anyone offer assistance with this issue?

Answer №1

When utilizing an ionic project, there's no need to write a barcode scanner in native Java code as there are plenty of plugins available for Cordova. Utilizing the ionic / cordova barcode scanner plugin would simplify your task.

However, for your specific situation:

Upon scanning the image, you will receive the image file path. Assign this path to a instance variable within the Java activity class. In your view, set up a setInterval timer and invoke a Java interface method that retrieves the file path. Once the file path is returned by the getter interface, clear both the Java instance variable and the interval.

Here's an example code snippet:

@JavascriptInterface
        public void scanBarCode() {
            Intent intent = new Intent(
                    "com.google.zxing.client.android.SCAN");
            intent.putExtra("SCAN_MODE", "QR_CODE_MODE,PRODUCT_MODE");
            startActivityForResult(intent, 0);
        }

 /** Read barcode from ZXing library */
        @JavascriptInterface
        public String getBarCode() {
            return (barcode!=null ? barcode : "");
        }

In your onActivityResult function, you will handle the image URL return.

public void onActivityResult(int requestCode, int resultCode, Intent intent) 

Next, in your JavaScript:

var barcodeTimer = setInterval(function () {
    var barcode = Android.getBarCode();
    if (barcode != "") {
        // assign it to your $scope
        $scope.$apply();
        clearInterval(barcodeTimer);
    }
}, 2000);

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

What is the best way to access a sub-object within a JSON object when the object's name is unknown?

I have a JSON object called data with the following content: {"query":{"pages":{"856":{"pageid":856,"ns":0,"title":"Announcements","revisions":[{"*":"* News item number one\n* News item number two"}]}}},"query-continue":{"revisions":{"rvstartid":1244 ...

Is Realm Database Compatible Across Different Platforms?

Is it possible to create a 'realm' using Realm Java and access it with Realm for iOS(8)? How well does the Realm Database system work across different platforms? I am thinking of developing a mobile app where I want to establish a 'realm&apo ...

Updating previous values in an array using Javascript's splice

In my game development project, circles are randomly displayed on a canvas. These circle objects are stored in an array and when the player collides with one of them, I aim to remove that specific object. Below is the current code snippet for handling the ...

Why is jQuery not defined in Browserify?

Dealing with this manually is becoming quite a hassle! I imported bootstrap dropdown.js and at the end of the function, there's }($); Within my shim, I specified jquery as a dependency 'bootstrap': { "exports": 'bootstrap', ...

Utilizing Angular 6 mergeMap for handling nested API requests

My goal is to retrieve a list of clients along with their accounts using the observe/subscribe pattern. Each client should have a list of their accounts associated with their client id. This is how I attempted it: this.httpService.getClients().subscribe( ...

Issue with retrieving relative time using Moment.js - fromNow()

I want to utilize moment.js to display relative time fromNow(), but I am encountering an issue where the values are being rounded and showing higher durations instead of exact completion times. For example, moment().subtract('s',110).fromNow() / ...

What criteria does Angular use to determine when the aot compiler should be utilized?

This page discusses the concept of modules in Angular and explains the two approaches to bootstrapping - dynamic and static. The configuration for these approaches is typically found in main.ts: // Using the browser platform with a compiler import { platf ...

Storing data in an Android app using db4o format

Currently, I am developing an Android application for a local community 'festival' that needs to sync with an online database every time it launches and then save the data on Android using db4o. The data is currently being sent to the app from a ...

"Enhancing AngularJS communication between controllers, services, and HTTP

Hey there! I have successfully packaged my REST API into an AngularJS service that gets injected into controllers. It's a pretty common practice, right? Now, what I need is for that service to catch any 401 response and somehow trigger a logout or re- ...

Relax with Express.js nested router

If I want to create REST endpoints with the following structure: /user/ /user/user_id /user/user_id/items/ /user/user_id/items/item_id Performing CRUD operations on each endpoint seems logical. For instance, a POST request to /user creates a new user, ...

Pass the DateTime object from ASP.NET to angularjs as a structured data type instead of converting it to a

I'm encountering an issue where I am sending a complex object from my ASP.NET backend to the AngularJS frontend. This object includes a DateTime property and a list of objects, each with their own DateTime property. These properties are all sent as st ...

Adding numerous entities individually

I am looking to insert multiple rows individually rather than in bulk: var setOrder = 0 for (exercise in exercisedWithSetsDTO) { viewModelScope.launch { var training = TrainingExercise( tra ...

Indentation differences between PHP and JavaScript

It's interesting to observe the different indentation conventions in various programming languages. Recently, I came across a code snippet from the PHP manual that caught my attention: switch ($i) { case "apple": echo "i is apple"; ...

Tips for styling custom buttons within the active editor popup of tinyMCE using CSS

Looking to enhance my tinyMCE active editor popup with custom CSS. Check out the screenshot provided for reference https://i.sstatic.net/vdVDF.png. Below you can find the code snippet used as a reference: tinymce.activeEditor.windowManager.open({ tit ...

Is there a way to update the parent component when changes occur in the child component?

I have been working on a book tracking application that allows users to keep track of the books they have read or plan to read. The app is built using Vue.js on the front end and Express.js on the server side. It consists of three lists or categories for o ...

Nuxt 3: Resolving Issues with Page and Layout Transitions

I've been attempting to incorporate layout transitions into my Nuxt 3 project, but unfortunately, it's not working as expected. I even resorted to replicating the code directly from the Nuxt transition documentation, only to face another failure. ...

Load specific information after button click in MVC

On my notes page, I wanted to enable users to add new notes by clicking a button. Here's the code snippet where I attempted to load the create note action result: <script type="text/javascript> (function() { $('#load-partial') ...

What is the best way to link a socket.id with an element in an array?

I am currently working on creating a chat-room where the names of connected users are shown in an 'Online Users' section. The following code snippet adds each user's name to an array and displays the contents of that array. However, if a u ...

Which specific event in NextJS is triggered only during the initial load?

I am working on a NextJS app and I want to implement an initial loading screen that only appears during the first load. Currently, the loading screen pops up not only on the initial load but also whenever a link is clicked that directs the user back to the ...

The Bootstrap carousel is stuck and not moving

I'm really struggling to figure out why the bootstrap carousel code isn't working for me. It's frustrating because I followed the example on the bootstrap website and only made minor customizations, so it should be functioning properly. I su ...