Example usage for org.json JSONArray optJSONObject

List of usage examples for org.json JSONArray optJSONObject

Introduction

In this page you can find the example usage for org.json JSONArray optJSONObject.

Prototype

public JSONObject optJSONObject(int index) 

Source Link

Document

Get the optional JSONObject associated with an index.

Usage

From source file:com.commontime.plugin.LocationManager.java

/**
 * Executes the request and returns PluginResult.
 *
 * @param action            The action to execute.
 * @param args              JSONArray of arguments for the plugin.
 * @param callbackContext   The callback id used when calling back into JavaScript.
 * @return                  True if the action was valid, false if not.
 *//*  www .  j  a  v a  2  s  .  c  o  m*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    if (action.equals("onDomDelegateReady")) {
        onDomDelegateReady(callbackContext);
    } else if (action.equals("disableDebugNotifications")) {
        disableDebugNotifications(callbackContext);
    } else if (action.equals("enableDebugNotifications")) {
        enableDebugNotifications(callbackContext);
    } else if (action.equals("disableDebugLogs")) {
        disableDebugLogs(callbackContext);
    } else if (action.equals("enableDebugLogs")) {
        enableDebugLogs(callbackContext);
    } else if (action.equals("appendToDeviceLog")) {
        appendToDeviceLog(args.optString(0), callbackContext);
    } else if (action.equals("startMonitoringForRegion")) {
        startMonitoringForRegion(args.optJSONObject(0), callbackContext);
    } else if (action.equals("stopMonitoringForRegion")) {
        stopMonitoringForRegion(args.optJSONObject(0), callbackContext);
    } else if (action.equals("startRangingBeaconsInRegion")) {
        startRangingBeaconsInRegion(args.optJSONObject(0), callbackContext);
    } else if (action.equals("stopRangingBeaconsInRegion")) {
        stopRangingBeaconsInRegion(args.optJSONObject(0), callbackContext);
    } else if (action.equals("isRangingAvailable")) {
        isRangingAvailable(callbackContext);
    } else if (action.equals("getAuthorizationStatus")) {
        getAuthorizationStatus(callbackContext);
    } else if (action.equals("requestWhenInUseAuthorization")) {
        requestWhenInUseAuthorization(callbackContext);
    } else if (action.equals("requestAlwaysAuthorization")) {
        requestAlwaysAuthorization(callbackContext);
    } else if (action.equals("getMonitoredRegions")) {
        getMonitoredRegions(callbackContext);
    } else if (action.equals("getRangedRegions")) {
        getRangedRegions(callbackContext);
    } else if (action.equals("requestStateForRegion")) {
        requestStateForRegion(args.optJSONObject(0), callbackContext);
    } else if (action.equals("registerDelegateCallbackId")) {
        registerDelegateCallbackId(args.optJSONObject(0), callbackContext);
    } else if (action.equals("isMonitoringAvailableForClass")) {
        isMonitoringAvailableForClass(args.optJSONObject(0), callbackContext);
    } else if (action.equals("isAdvertisingAvailable")) {
        isAdvertisingAvailable(callbackContext);
    } else if (action.equals("isAdvertising")) {
        isAdvertising(callbackContext);
    } else if (action.equals("startAdvertising")) {
        startAdvertising(args.optJSONObject(0), callbackContext);
    } else if (action.equals("stopAdvertising")) {
        stopAdvertising(callbackContext);
    } else if (action.equals("isBluetoothEnabled")) {
        isBluetoothEnabled(callbackContext);
    } else if (action.equals("enableBluetooth")) {
        enableBluetooth(callbackContext);
    } else if (action.equals("disableBluetooth")) {
        disableBluetooth(callbackContext);
    } else {
        return false;
    }
    return true;
}

From source file:com.phonegap.App.java

/**
 * Executes the request and returns PluginResult.
 *
 * @param action        The action to execute.
 * @param args          JSONArry of arguments for the plugin.
 * @param callbackId    The callback id used when calling back into JavaScript.
 * @return              A PluginResult object with a status and message.
 *///w w w.  j  ava2  s.co  m
public PluginResult execute(String action, JSONArray args, String callbackId) {
    PluginResult.Status status = PluginResult.Status.OK;
    String result = "";

    try {
        if (action.equals("clearCache")) {
            this.clearCache();
        } else if (action.equals("loadUrl")) {
            this.loadUrl(args.getString(0), args.optJSONObject(1));
        } else if (action.equals("cancelLoadUrl")) {
            this.cancelLoadUrl();
        } else if (action.equals("clearHistory")) {
            this.clearHistory();
        } else if (action.equals("addService")) {
            this.addService(args.getString(0), args.getString(1));
        }
        return new PluginResult(status, result);
    } catch (JSONException e) {
        return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
    }
}

From source file:org.akop.ararat.io.WSJFormatter.java

private static void readClues(Crossword.Builder builder, JSONObject copyObj, Grid grid) {
    JSONArray cluesArray = copyObj.optJSONArray("clues");
    if (cluesArray == null) {
        throw new FormatException("Missing 'data.copy.clues[]'");
    } else if (cluesArray.length() != 2) {
        throw new FormatException("Unexpected clues length of '" + cluesArray.length() + "'");
    }/*from w  w  w .  j  a v  a 2s  .  c  o m*/

    JSONArray wordsArray = copyObj.optJSONArray("words");
    if (wordsArray == null) {
        throw new FormatException("Missing 'data.copy.words[]'");
    }

    // We'll need this to assign x/y locations to each clue
    SparseArray<Word> words = new SparseArray<>();
    for (int i = 0, n = wordsArray.length(); i < n; i++) {
        Word word;
        try {
            word = Word.parseJSON(wordsArray.optJSONObject(i));
        } catch (Exception e) {
            throw new FormatException("Error parsing 'data.copy.words[" + i + "]'", e);
        }

        words.put(word.mId, word);
    }

    // Go through the list of clues
    for (int i = 0, n = cluesArray.length(); i < n; i++) {
        JSONObject clueObj = cluesArray.optJSONObject(i);
        if (clueObj == null) {
            throw new FormatException("'data.copy.clues[" + i + "]' is null");
        }

        JSONArray subcluesArray = clueObj.optJSONArray("clues");
        if (subcluesArray == null) {
            throw new FormatException("Missing 'data.copy.clues[" + i + "].clues'");
        }

        int dir;
        String clueDir = clueObj.optString("title");
        if ("Across".equalsIgnoreCase(clueDir)) {
            dir = Crossword.Word.DIR_ACROSS;
        } else if ("Down".equalsIgnoreCase(clueDir)) {
            dir = Crossword.Word.DIR_DOWN;
        } else {
            throw new FormatException("Invalid direction: '" + clueDir + "'");
        }

        for (int j = 0, o = subcluesArray.length(); j < o; j++) {
            JSONObject subclue = subcluesArray.optJSONObject(j);
            Word word = words.get(subclue.optInt("word", -1));
            if (word == null) {
                throw new FormatException(
                        "No matching word for clue at 'data.copy.clues[" + i + "].clues[" + j + "].word'");
            }

            Crossword.Word.Builder wb = new Crossword.Word.Builder().setDirection(dir)
                    .setHint(subclue.optString("clue")).setNumber(subclue.optInt("number"))
                    .setStartColumn(word.mCol).setStartRow(word.mRow);

            if (dir == Crossword.Word.DIR_ACROSS) {
                for (int k = word.mCol, l = 0; l < word.mLen; k++, l++) {
                    Square square = grid.mSquares[word.mRow][k];
                    if (square == null) {
                        throw new FormatException(
                                "grid[" + word.mRow + "][" + k + "] is null (it shouldn't be)");
                    }
                    wb.addCell(square.mChar, 0);
                }
            } else {
                for (int k = word.mRow, l = 0; l < word.mLen; k++, l++) {
                    Square square = grid.mSquares[k][word.mCol];
                    if (square == null) {
                        throw new FormatException(
                                "grid[" + k + "][" + word.mCol + "] is null (it shouldn't be)");
                    }
                    wb.addCell(square.mChar, 0);
                }
            }

            builder.addWord(wb.build());
        }
    }
}

From source file:com.appsimobile.appsii.module.weather.ImageDownloadHelper.java

public static void getEligiblePhotosFromResponse(@Nullable JSONObject jsonObject, List<PhotoInfo> result,
        int minDimension) {
    result.clear();/* w ww  . jav  a 2  s. c  om*/

    if (jsonObject == null)
        return;

    JSONObject photos = jsonObject.optJSONObject("photos");
    if (photos == null)
        return;

    JSONArray photoArr = photos.optJSONArray("photo");
    if (photoArr == null)
        return;

    int N = photoArr.length();
    for (int i = 0; i < N; i++) {
        JSONObject object = photoArr.optJSONObject(i);
        if (object == null)
            continue;
        String id = object.optString("id");
        if (TextUtils.isEmpty(id))
            continue;
        String urlH = urlFromImageObject(object, "url_h", "width_h", "height_h", minDimension - 100);
        String urlO = urlFromImageObject(object, "url_o", "width_o", "height_o", minDimension - 100);

        if (urlH != null) {
            result.add(new PhotoInfo(id, urlH));
        } else if (urlO != null) {
            result.add(new PhotoInfo(id, urlO));
        }
    }

}

From source file:com.nascent.android.glass.glasshackto.greenpfinder.model.GreenPSpots.java

/**
 * Populates the internal places list from places found in a JSON string. This string should
 * contain a root object with a "landmarks" property that is an array of objects that represent
 * places. A place has three properties: name, latitude, and longitude.
 *//*from  w w w . ja v a  2s  .com*/
private void populatePlaceList(String jsonString) {
    try {
        JSONObject json = new JSONObject(jsonString);
        JSONArray array = json.optJSONArray("carparks");

        if (array != null) {
            for (int i = 0; i < array.length(); i++) {
                JSONObject object = array.optJSONObject(i);
                ParkingLot parkingLot = jsonObjectToParkingLot(object);
                if (parkingLot != null) {
                    mParkingLots.add(parkingLot);
                }
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, "Could not parse landmarks JSON string", e);
    }
}

From source file:com.phelps.liteweibo.model.weibo.CommentList.java

public static CommentList parse(String jsonString) {
    if (TextUtils.isEmpty(jsonString)) {
        return null;
    }//from w  w  w.  jav a 2s.  co m

    CommentList comments = new CommentList();
    try {
        JSONObject jsonObject = new JSONObject(jsonString);
        comments.previous_cursor = jsonObject.optString("previous_cursor", "0");
        comments.next_cursor = jsonObject.optString("next_cursor", "0");
        comments.total_number = jsonObject.optInt("total_number", 0);

        JSONArray jsonArray = jsonObject.optJSONArray("comments");
        if (jsonArray != null && jsonArray.length() > 0) {
            int length = jsonArray.length();
            comments.commentList = new ArrayList<Comment>(length);
            for (int ix = 0; ix < length; ix++) {
                comments.commentList.add(Comment.parse(jsonArray.optJSONObject(ix)));
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return comments;
}

From source file:com.sina.weibo.sdk_lib.openapi.models.OffsetGeo.java

public static OffsetGeo parse(String jsonString) {
    if (TextUtils.isEmpty(jsonString)) {
        return null;
    }//from w  w w  . j a v  a  2s  .c o  m

    OffsetGeo offsetGeo = new OffsetGeo();
    try {
        JSONObject jsonObject = new JSONObject(jsonString);

        JSONArray jsonArray = jsonObject.optJSONArray("geos");
        if (jsonArray != null && jsonArray.length() > 0) {
            int length = jsonArray.length();
            offsetGeo.Geos = new ArrayList<Coordinate>(length);
            for (int ix = 0; ix < length; ix++) {
                offsetGeo.Geos.add(Coordinate.parse(jsonArray.optJSONObject(ix)));
            }
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }

    return offsetGeo;
}

From source file:com.hyunnyapp.easycursor.jsoncursor.JsonFieldAccessor.java

private void populateMethodList(final JSONArray array) {
    int count = 0;
    final JSONObject obj = array.optJSONObject(0);

    @SuppressWarnings("unchecked")
    final Iterator<String> keyIterator = obj.keys();
    while (keyIterator.hasNext()) {
        final String key = keyIterator.next();
        mPropertyList.add(key);// w  w w  .j  a  v  a2s .c  om
        mPropertyToIndexMap.put(key, count);
        count++;
    }
}

From source file:org.catnut.fragment.TransientUsersFragment.java

private Response<List<TransientUser>> parseNetworkResponse(NetworkResponse response) {
    try {/*ww  w  .  j a  v a2 s .c  om*/
        String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        JSONObject result = new JSONObject(jsonString);
        // set next_cursor
        mNext_cursor = result.optInt(User.next_cursor);
        mTotal_number = result.optInt(User.total_number);
        JSONArray array = result.optJSONArray(User.MULTIPLE);
        if (array != null) {
            List<TransientUser> users = new ArrayList<TransientUser>(array.length());
            for (int i = 0; i < array.length(); i++) {
                users.add(TransientUser.convert(array.optJSONObject(i)));
            }
            return Response.success(users, HttpHeaderParser.parseCacheHeaders(response));
        } else {
            throw new RuntimeException("no users found!");
        }
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException je) {
        return Response.error(new ParseError(je));
    } catch (Exception ex) {
        return Response.error(new ParseError(ex));
    }
}

From source file:se.frostyelk.cordova.amazon.ads.AmazonAds.java

/**
 * This is the main method for the Amazon Ads plugin. All API calls go
 * through here. This method determines the action, and executes the
 * appropriate call./*from w ww  .  ja  v  a 2s . c  om*/
 *
 * @param action
 *            The action that the plugin should execute.
 * @param inputs
 *            The input parameters for the action.
 * @param callbackContext
 *            The callback context.
 * @return A PluginResult representing the result of the provided action. A
 *         status of INVALID_ACTION is returned if the action is not
 *         recognized.
 */
@Override
public boolean execute(String action, JSONArray inputs, CallbackContext callbackContext) throws JSONException {
    PluginResult result = null;

    if (ACTION_CREATE_INTERSTITIAL_AD.equals(action)) {
        JSONObject options = inputs.optJSONObject(0);
        result = executeCreateInterstitialAd(options, callbackContext);
    } else if (ACTION_SHOW_INTERSTITIAL_AD.equals(action)) {
        result = executeShowInterstitialAd(callbackContext);
    } else {
        result = new PluginResult(Status.INVALID_ACTION);
    }

    if (result != null)
        callbackContext.sendPluginResult(result);

    return true;
}