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.
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
Creating a JSON Array in Java
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()); result.setKeepCallback(true); callbacks.sendPluginResult(result);
JSONObject item = new JSONObject(); item.put("name", "filename.java"); callbacks.success(item.toString());