Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a array or other collections elements type from phonegap android plugin

here is a part of my testing code in a java plugin (i'm using phonegap 2.7).

public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {

  try {

      String[] result;
      result = new String[10];
      result[0] = "test1 success";
      result[1] = "test2 success";
      callbackContext.success(result);  //error

  } catch(Exception ee) {
      System.out.print("ee:"+ee.getMessage());
  }
  return true;
}

My questions are :

  1. how to return the array from android phonegap plugin so i can get the array in the javascript?

  2. which data type is better than array (JSONArray?) to be returned?

thanks

like image 416
hkguile Avatar asked Mar 23 '23 17:03

hkguile


1 Answers

PluginResult class is your friend:

public PluginResult(Status status, JSONObject message) {
    this.status = status.ordinal();
    this.message = (message != null) ? message.toString(): "null";
}

or

public PluginResult(Status status, String message) {
    this.status = status.ordinal();
    this.message = JSONObject.quote(message);
}

In your case it accepts either a json object or a string. So to return a json array you need

JSONObject json = new JSONObject();
json.put("foo", "bar");

callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, json));
like image 91
UpCat Avatar answered Apr 06 '23 03:04

UpCat