Learn how to send data from java to javascript with cordova

In cordova, you may need to return some data to the view (not only simple strings). This data can be efficiently sent to the view with JSON, however we will not create a JSON string from an array manually because that's not a good practice.

To send information from java to javascript in cordova with Java android :

Include the required components

We need to include the following components in the class, then we will be able to create json arrays and objects (if you use try and catch block , you need to include the JSONException).

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

Creating a JSON Object in Java

In javascript the creation of a object is really easy, you just need to assign the property name to a object and that's it (with point or brackets notation). With java is simple too, but different, we will create a variable with type JSONObject and we will use the PUT function to add a key.

JSONObject item = new JSONObject();
item.put("name", "filename.java");
// in javascript this is something like
// {filepath:"aimaginarypath",name:"filename.java"}

the variable item contains name and filepath keys as a normal javascript object.

Creating a JSON Array in Java

In javascript we need to call the push function to add a item to an existent array. With java is the same, only with other name (add).

JSONArray jsonArray = new JSONArray();
jsonArray.put("item number 1");
jsonArray.put("item number 2");
// in javascript this is something like :
// ["item number 1","item number 2"]


To send the array or object, we will call the toString method on the variables. here are 2 ways to send results in cordova (remember that callbacks = the callbackContext variable of your class):

Asynchronous (using threadPool)

JSONArray jsonArray = new JSONArray();
jsonArray.put("item number 1");

// send the JSONArray using jsonArray.toString();
PluginResult result = new PluginResult(PluginResult.Status.OK, jsonArray.toString());


JSONObject item = new JSONObject();
item.put("name", "filename.java");


Then you only need to parse it with Javascript (JSON.parse(jsonstring)), have fun !

Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.