Running the Phonegap (Cordova 3.3.0) Plugin within a Java Environment

Is it possible to call a PhoneGap plugin from Java without going through the browser? For example, calling a JavaScript plugin like this: "cordova.exec(successCallback, failureCallback, 'CallListPlugin', 'list', params)"

I am curious about how to make this call directly from the MainActivity. Any insights or suggestions?

Thank you!

CallListPlugin.java

package com.example.app;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
// more imports...

public class CallListPlugin extends CordovaPlugin {

    // Actions
    private static final String ACTION = "list";
    private static final String CONTACT_ACTION = "contact";
    private static final String SHOW_ACTION = "show";

    @Override
    public boolean execute(String action, JSONArray data, CallbackContext callbackContext) {
        boolean actionValid = true;

        if (ACTION.equals(action)) {
            try {
                int limit = -1;

                // Limit by date
                if (!data.isNull(0)) {
                    String d = data.getString(0);
                    // logic for time period limit...
                } 

                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                // more logic...

                JSONObject callInfo = getCallListing(limiter);
                PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, callInfo);
                callbackContext.sendPluginResult(pluginResult);
                callbackContext.success();

            } catch (JSONException jsonEx) {
                Log.d(TAG, "Got JSON Exception " + jsonEx.getMessage());
                callbackContext.error(jsonEx.getMessage());
                actionValid = false;
            }
        } else if (SHOW_ACTION.equals(action)) {
            try {
                if (!data.isNull(0)) {
                    viewContact(data.getString(0));
                } 
            } catch (JSONException | Exception e) {
                Log.d(TAG, "Exception: " + e.getMessage());
                callbackContext.error(e.getMessage());
                actionValid = false;
            } 
        } else if (CONTACT_ACTION.equals(action)) {
            try {
                String contactInfo = getContactNameFromNumber(data.getString(0));
                PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, contactInfo);
                callbackContext.sendPluginResult(pluginResult);
                callbackContext.success();
            } catch (JSONException | Exception e) {
                Log.d(TAG, "Error: " + e.getMessage());
                callbackContext.error(e.getMessage());
                actionValid = false;
            }
        } else {
            actionValid = false;
            Log.d(TAG, "Invalid action: " + action);
        }

        return actionValid;
    }

    // Other methods and functions...

}

Answer №1

To incorporate the mentioned package into your primary Java file, you will need to use the following import statement:

import com.leafcut.ctrac.CallListPlugin;

Once imported, you will gain access to all the public methods available within CallListPlugin. For instance:

CallListPlugin.execute(String some_string, JSONArray some_array, CallbackContext some_context);

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

The use of lambda expressions in -source 1.7 is not supported when working with Android SDK in IntelliJ

Greetings everyone I have noticed that there are numerous inquiries regarding this issue, and I have gone through quite a few of them. However, none of them seem to provide a definitive "solution." The typical response is to adjust the Language level to ...

A method for automatically refreshing a webpage once it switches between specific resolutions

On my page www.redpeppermedia.in/tc24_beta/, it functions well at a resolution of over 980px. However, when the resolution is brought down to 768px, the CSS and media queries alter the layout. But upon refreshing the page at 768px, everything corrects itse ...

What is the method for invoking a function with arguments within an HTML `<p>` element?

I am looking to display like and dislike percentages on cards. <v-card v-if="software[2] == searched || searched == ''" class="software-card" > <h3>{{ software[2] }}</h3> ...

Saving JSON format in VueX State Management

I'm relatively new to using Vue/VueX and I am exploring methods for storing JSON data in the VueX state. Initially, it seemed like a simple task: state { jsonthing: { ... } } However, I encountered an issue where getters return an Observer type ins ...

Encountering 404 errors with JRebel when making changes to web-fragments

Struggling to integrate JRebel with a web project that includes web fragments. Despite successfully deploying changes after code edits, the web application suddenly starts displaying 404 errors for all pages and requests. Any insights on what could be cau ...

Discover how to iterate through an array following a map operation and generate a new array based on conditional statements

data.risk.scatterIndices.investments.map((el: any) => el.name) || [] I have a mapping function that generates an array like this: ["pension","realestate","balance","kupot"] This is the condition I want to use t ...

How to message someone privately in a public Discord channel using discord.js

Can someone help me figure out how to create a message in discord.js version 12.5.3 that only I can see? I know how to send messages to channels using message.channel.send, but I'm not sure how to make a message visible only to myself. Thank you! ...

Why isn't the nested intricate directive being executed?

After watching a tutorial on YouTube by John Lindquist from egghead.io, where he discussed directives as components and containers, I decided to implement a similar structure but with a more dynamic approach. In his example, it looked something like this ...

From JSON to PNG in one simple step with Fabric.js

I am looking for a way to generate PNG thumbnails from saved stringified JSON data obtained from fabric.js. Currently, I store the JSON data in a database after saving it from the canvas. However, now I want to create a gallery of PNG thumbnails using thi ...

Weird problem with handling dates in JavaScript and PHP

I'm having trouble with dates in JavaScript and PHP. <?php $mydate = date('2012-05-02 17:00:00'); echo 'Today in PHP --'.$mydate; $mytimstamp = strtotime($mydate); echo '<br/>My PHP unix timestamp --'.$mytimst ...

What is the best method for checking for JavaScript errors when using Selenium WebDriver in conjunction with NodeJS?

When it comes to coding in JavaScript, not Java, my focus is on running a specific website like foo.com. I typically set it up as follows: var webdriver = require("selenium-webdriver"); By = webdriver.By, until = webdriver.until; var chrome = req ...

What is the best way to access a particular property of an object?

Currently, I am successfully sending data to Mongo and storing user input information in the backend. In the console, an interceptor message confirms that the data is received from MongoDB. However, I am struggling to extract specific properties such as th ...

Encountering an issue with Angular 2 that is causing an error: Uncaught SyntaxError due to an unexpected

I'm facing an issue while trying to incorporate Angular 2 into my existing project. Here are the codes I'm using: <script src="https://code.angularjs.org/2.0.0-beta.0/angular2-polyfills.js"></script> <script src="https://code.angu ...

Issue with initializing a list using constructor in Spring Data MongoDB

Looking to utilize spring-data-mongodb-1.5.4 along with mongodb-driver-3.4.2 In my project, I have defined a class called Hotel public class Hotel { private String name; private int pricePerNight; private Address address; ...

I am sorry, but it seems like there is an issue with the definition of global in

I have a requirement to transform an XML String into JSON in order to retrieve user details. The approach I am taking involves utilizing the xml2js library. Here is my TypeScript code: typescript.ts sendXML(){ console.log("Inside sendXML method") ...

The Restlet client fails to retrieve any data

Having a jax-rs annotated interface public interface Store { @Path("/apipath") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Token login(@BeanParam Header header, ...

Which Express.js template allows direct usage of raw HTML code?

I am in search of a template that utilizes pure HTML without any alterations to the language, similar to Jade but keeping the HTML as is. The reason behind this inquiry is: I prefer the simplicity and clarity of HTML I would like to be able to easily vi ...

Learning to control the JavaScript countdown clock pause and play functionality

How can I control the countdown timer to play and pause, allowing me to resume at the exact time it was paused? At the start, the timer is set to play. Please keep in mind that the button appears empty because the font-awesome package was not imported, b ...

Challenges arise when using node Serialport for writing data

My current project involves sending commands from a node server to an Arduino Mega board and receiving responses. Everything works smoothly when I limit the calls to SERIALPORT.write to once every 1000ms. However, if I attempt to increase the frequency, I ...

Include personalized headers to the 'request'

I have configured my express server to proxy my API using the following setup: // Proxy api calls app.use('/api', function (req, res) { let url = config.API_HOST + req.url req.pipe(request(url)).pipe(res) }) In this instance, confi ...