简体   繁体   中英

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

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM