Example usage for org.json JSONArray optInt

List of usage examples for org.json JSONArray optInt

Introduction

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

Prototype

public int optInt(int index, int defaultValue) 

Source Link

Document

Get the optional int value associated with an index.

Usage

From source file:re.notifica.cordova.NotificarePlugin.java

/**
 * Fetch inbox items//from   ww  w. j a  va  2 s.  c o  m
 * @param args
 * @param callbackContext
 */
protected void fetchInbox(JSONArray args, final CallbackContext callbackContext) {
    Log.d(TAG, "FETCHINBOX");
    if (Notificare.shared().getInboxManager() != null) {
        int size = Notificare.shared().getInboxManager().getItems().size();
        int limit = args.optInt(1, DEFAULT_LIST_SIZE);
        if (limit <= 0) {
            limit = DEFAULT_LIST_SIZE;
        }
        int skip = args.optInt(0);
        if (skip < 0) {
            skip = 0;
        }
        if (skip > size) {
            skip = size;
        }
        int end = limit + skip;
        if (end > size) {
            end = size;
        }
        List<NotificareInboxItem> items = new ArrayList<NotificareInboxItem>(
                Notificare.shared().getInboxManager().getItems()).subList(skip, end);
        JSONArray inbox = new JSONArray();
        for (NotificareInboxItem item : items) {
            try {
                JSONObject result = new JSONObject();
                result.put("itemId", item.getItemId());
                result.put("notification", item.getNotification().getNotificationId());
                result.put("message", item.getNotification().getMessage());
                result.put("status", item.getStatus());
                result.put("timestamp", dateFormatter.format(item.getTimestamp()));
                inbox.put(result);
            } catch (JSONException e) {
                // Ignore this item
                Log.w(TAG, "failed to serialize inboxitem: " + e.getMessage());
            }
        }
        if (callbackContext == null) {
            return;
        }
        JSONObject results = new JSONObject();
        try {
            results.put("inbox", inbox);
            results.put("total", size);
            results.put("unread", Notificare.shared().getInboxManager().getUnreadCount());
        } catch (JSONException e) {
            Log.w(TAG, "failed to serialize inbox: " + e.getMessage());
        }
        callbackContext.success(results);
    } else {
        if (callbackContext == null) {
            return;
        }
        callbackContext.error("No inbox manager");
    }
}

From source file:com.trellmor.berrytube.BerryTubeIOCallback.java

/**
 * @see io.socket.IOCallback#on(java.lang.String, io.socket.IOAcknowledge,
 *      java.lang.Object[])//from w ww. j  a v  a  2  s  .  co  m
 */
public void on(String event, IOAcknowledge ack, Object... args) {
    if (event.compareTo("chatMsg") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject jsonMsg = (JSONObject) args[0];

            try {
                berryTube.getHandler()
                        .post(berryTube.new ChatMsgTask(new ChatMessage(jsonMsg.getJSONObject("msg"))));
            } catch (JSONException e) {
                Log.e(TAG, "chatMsg", e);
            }
        } else
            Log.w(TAG, "chatMsg message is not a JSONObject");
    } else if (event.compareTo("setNick") == 0) {
        if (args.length >= 1 && args[0] instanceof String) {
            berryTube.getHandler().post(berryTube.new SetNickTask((String) args[0]));
        } else
            Log.w(TAG, "setNick message is not a String");
    } else if (event.compareTo("loginError") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject error = (JSONObject) args[0];
            berryTube.getHandler()
                    .post(berryTube.new LoginErrorTask(error.optString("message", "Login failed")));
        }
    } else if (event.compareTo("userJoin") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject user = (JSONObject) args[0];
            try {
                berryTube.getHandler().post(berryTube.new UserJoinPartTask(new ChatUser(user),
                        BerryTube.UserJoinPartTask.ACTION_JOIN));
            } catch (JSONException e) {
                Log.e(TAG, "userJoin", e);
            }
        } else
            Log.w(TAG, "userJoin message is not a JSONObject");
    } else if (event.compareTo("newChatList") == 0) {
        berryTube.getHandler().post(berryTube.new UserResetTask());
        if (args.length >= 1 && args[0] instanceof JSONArray) {
            JSONArray users = (JSONArray) args[0];
            for (int i = 0; i < users.length(); i++) {
                JSONObject user = users.optJSONObject(i);
                if (user != null) {
                    try {
                        berryTube.getHandler().post(berryTube.new UserJoinPartTask(new ChatUser(user),
                                BerryTube.UserJoinPartTask.ACTION_JOIN));
                    } catch (JSONException e) {
                        Log.e(TAG, "newChatList", e);
                    }
                }
            }
        } else
            Log.w(TAG, "newChatList message is not a JSONArray");
    } else if (event.compareTo("userPart") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject user = (JSONObject) args[0];
            try {
                berryTube.getHandler().post(berryTube.new UserJoinPartTask(new ChatUser(user),
                        BerryTube.UserJoinPartTask.ACTION_PART));
            } catch (JSONException e) {
                Log.e(TAG, "userPart", e);
            }
        } else
            Log.w(TAG, "userPart message is not a JSONObject");
    } else if (event.compareTo("drinkCount") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject drinks = (JSONObject) args[0];
            berryTube.getHandler().post(berryTube.new DrinkCountTask(drinks.optInt("drinks")));
        }
    } else if (event.compareTo("kicked") == 0) {
        berryTube.getHandler().post(berryTube.new KickedTask());
    } else if (event.compareTo("newPoll") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject poll = (JSONObject) args[0];
            ChatMessage msg;

            // Send chat message for new poll
            try {
                msg = new ChatMessage(poll.getString("creator"), poll.getString("title"),
                        ChatMessage.EMOTE_POLL, 0, 0, false, 1);
                berryTube.getHandler().post(berryTube.new ChatMsgTask(msg));
            } catch (JSONException e) {
                Log.e(TAG, "newPoll", e);
            }

            // Create new poll
            try {
                berryTube.getHandler().post(berryTube.new NewPollTask(new Poll(poll)));
            } catch (JSONException e) {
                Log.e(TAG, "newPoll", e);
            }
        }
    } else if (event.compareTo("updatePoll") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject poll = (JSONObject) args[0];
            try {
                JSONArray votes = poll.getJSONArray("votes");
                int[] voteArray = new int[votes.length()];
                for (int i = 0; i < votes.length(); i++) {
                    voteArray[i] = votes.optInt(i, -1);
                }
                berryTube.getHandler().post(berryTube.new UpdatePollTask(voteArray));
            } catch (JSONException e) {
                Log.e(TAG, "updatePoll", e);
            }
        }
    } else if (event.compareTo("clearPoll") == 0) {
        berryTube.getHandler().post(berryTube.new ClearPollTask());
    } else if (event.compareTo("forceVideoChange") == 0 || event.compareTo("hbVideoDetail") == 0) {
        if (args.length >= 1 && args[0] instanceof JSONObject) {
            JSONObject videoMsg = (JSONObject) args[0];
            try {
                JSONObject video = videoMsg.getJSONObject("video");
                String name = URLDecoder.decode(video.getString("videotitle"), "UTF-8");
                String id = video.getString("videoid");
                String type = video.getString("videotype");
                berryTube.getHandler().post(berryTube.new NewVideoTask(name, id, type));
            } catch (JSONException | UnsupportedEncodingException e) {
                Log.w(TAG, e);
            }
        }
    }
}

From source file:com.trellmor.berrytube.Poll.java

/**
 * Constructs a <code>Poll</code> from a <code>JSONObject<code>
 * // w w w  . jav  a2  s  .  c om
 * @param poll <code>JSONObject<code> containing the poll data
 * @throws JSONException
 */
public Poll(JSONObject poll) throws JSONException {
    mTitle = poll.getString("title");
    mCreator = poll.getString("title");
    mObscure = poll.getBoolean("obscure");

    JSONArray options = poll.getJSONArray("options");
    for (int i = 0; i < options.length(); i++) {
        mOptions.add(options.getString(i));
    }

    JSONArray votes = poll.getJSONArray("votes");
    for (int i = 0; i < votes.length(); i++) {
        mVotes.add(votes.optInt(i, -1));
    }
}

From source file:com.commontime.plugin.notification.Notification.java

/**
 * Cancel multiple local notifications./*from   w  w  w.  j  a v  a2 s .co m*/
 *
 * @param ids Set of local notification IDs
 */
private void cancel(JSONArray ids) {
    for (int i = 0; i < ids.length(); i++) {
        int id = ids.optInt(i, 0);

        NotificationWrapper notification = getNotificationMgr().cancel(id);

        if (notification != null) {
            fireEvent("cancel", notification);
        }
    }
}

From source file:com.commontime.plugin.notification.Notification.java

/**
 * Clear multiple local notifications without canceling them.
 *
 * @param ids Set of local notification IDs
 */// w  ww .j  av a2s  . c  om
private void clear(JSONArray ids) {
    for (int i = 0; i < ids.length(); i++) {
        int id = ids.optInt(i, 0);

        NotificationWrapper notification = getNotificationMgr().clear(id);

        if (notification != null) {
            fireEvent("clear", notification);
        }
    }
}

From source file:plugin.geolocation.GeoBroker.java

/**
 * Executes the request and returns PluginResult.
 *
 * @param action       The action to execute.
 * @param args       JSONArry of arguments for the plugin.
 * @param callbackContext   The callback id used when calling back into JavaScript.
 * @return          True if the action was valid, or false if not.
 *///from w w w .j  a  va2s  . co m
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (locationManager == null) {
        locationManager = (LocationManager) this.cordova.getActivity()
                .getSystemService(Context.LOCATION_SERVICE);
    }
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
            || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        if (networkListener == null) {
            networkListener = new NetworkListener(locationManager, this);
        }
        if (gpsListener == null) {
            gpsListener = new GPSListener(locationManager, this);
        }

        if (action.equals("getLocation")) {
            boolean enableHighAccuracy = args.getBoolean(0);
            int maximumAge = args.getInt(1);
            String provider = (enableHighAccuracy
                    && locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
                            ? LocationManager.GPS_PROVIDER
                            : LocationManager.NETWORK_PROVIDER;
            Location last = this.locationManager.getLastKnownLocation(provider);
            // Check if we can use lastKnownLocation to get a quick reading and use less battery
            if (last != null && (System.currentTimeMillis() - last.getTime()) <= maximumAge) {
                PluginResult result = new PluginResult(PluginResult.Status.OK, this.returnLocationJSON(last));
                callbackContext.sendPluginResult(result);
            } else {
                this.getCurrentLocation(callbackContext, enableHighAccuracy, args.optInt(2, 60000));
            }
        } else if (action.equals("addWatch")) {
            String id = args.getString(0);
            boolean enableHighAccuracy = args.getBoolean(1);
            this.addWatch(id, callbackContext, enableHighAccuracy);
        } else if (action.equals("clearWatch")) {
            String id = args.getString(0);
            this.clearWatch(id);
        } else {
            return false;
        }
    } else {
        PluginResult.Status status = PluginResult.Status.NO_RESULT;
        String message = "Location API is not available for this device.";
        PluginResult result = new PluginResult(status, message);
        callbackContext.sendPluginResult(result);
    }
    return true;
}

From source file:com.samsung.spen.SpenPlugin.java

/**
 * //w  w  w  . ja  va  2  s  .  c o m
 * @param args
 *                 JSON array of options sent from the script.
 * @param surfaceType
 *                int
 * @param callbackContext
 *                CallbackContext
 * @return   options
 *                SpenTrayBarOptions
 * @throws JSONException
 */
private SpenTrayBarOptions createTrayBarOptions(JSONArray args, int surfaceType,
        CallbackContext callbackContext) throws JSONException {
    if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
        Log.d(TAG, "Inside createTrayBarOptions");
    }

    String tempId = args.getString(ID);
    if (tempId != null) {
        tempId = tempId.trim();
        if (tempId.length() > MAX_ID_LENGTH) {
            tempId = tempId.substring(0, MAX_ID_LENGTH);
        }
    }

    final String id = tempId;
    if (id == null || id.equals("") || id.equals("null") || !id.matches("^[ !#-)+-.0-9;=@-Z^-{}~]+$")) {
        SpenException.sendPluginResult(SpenExceptionType.INVALID_SURFACE_ID, callbackContext);
        return null;
    }

    int sPenFlags = args.optInt(SPEN_FLAGS, Integer.MIN_VALUE);
    if (sPenFlags == Integer.MIN_VALUE || sPenFlags > Utils.MAX_FLAGS_VALUE
            || sPenFlags < Utils.MIN_FLAGS_VALUE) {
        SpenException.sendPluginResult(SpenExceptionType.INVALID_FLAGS, callbackContext);
        return null;
    }

    int returnType = args.optInt(RETURN_TYPE);
    if (returnType != Utils.RETURN_TYPE_IMAGE_DATA && returnType != Utils.RETURN_TYPE_IMAGE_URI
            && returnType != Utils.RETURN_TYPE_TEXT) {

        SpenException.sendPluginResult(SpenExceptionType.INVALID_RETURN_TYPE, callbackContext);
        return null;
    }

    String backgroundColor = args.getString(BACKGROUND_COLOR);

    String imagePath = args.getString(IMAGE_PATH);
    if (imagePath.equals("") || imagePath.equals("null")) {
        imagePath = null;
    } else {
        imagePath = Uri.decode(imagePath);
        String truncatedPath = truncateQueryPart(imagePath);
        File file = new File(truncatedPath);
        if (file.exists()) {
            imagePath = truncatedPath;
        }
    }

    int bgImageScaleType = args.optInt(BACKGROUND_IMAGE_SCALE_TYPE);
    if (bgImageScaleType != Utils.BACKGROUND_IMAGE_MODE_CENTER
            && bgImageScaleType != Utils.BACKGROUND_IMAGE_MODE_FIT
            && bgImageScaleType != Utils.BACKGROUND_IMAGE_MODE_STRETCH
            && bgImageScaleType != Utils.BACKGROUND_IMAGE_MODE_TILE) {
        bgImageScaleType = Utils.BACKGROUND_IMAGE_MODE_FIT;
    }

    int imageUriScaleType = args.optInt(IMAGE_URI_SCALE_TYPE);
    if (imageUriScaleType != Utils.IMAGE_URI_MODE_CENTER && imageUriScaleType != Utils.IMAGE_URI_MODE_FIT
            && imageUriScaleType != Utils.IMAGE_URI_MODE_TILE
            && imageUriScaleType != Utils.IMAGE_URI_MODE_STRETCH) {
        imageUriScaleType = Utils.IMAGE_URI_MODE_FIT;
    }

    if (surfaceType == Utils.SURFACE_INLINE) {
        if ((sPenFlags & Utils.FLAG_ADD_PAGE) == Utils.FLAG_ADD_PAGE) {
            if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
                Log.d(TAG, "Add Page is not supported in Inline");
            }
            sPenFlags = sPenFlags & ~Utils.FLAG_ADD_PAGE;
        }
    } else if (surfaceType == Utils.SURFACE_POPUP) {

        if ((sPenFlags & Utils.FLAG_EDIT) == Utils.FLAG_EDIT) {
            if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
                Log.d(TAG, "Edit Page is not supported in Popup");
            }
            sPenFlags = sPenFlags & ~Utils.FLAG_EDIT;
        }

        if ((sPenFlags & Utils.FLAG_PEN) == Utils.FLAG_PEN) {
            if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
                Log.d(TAG, "Pen option is provided by default, is not configurable in Popup");
            }
            sPenFlags = sPenFlags & ~Utils.FLAG_PEN;

        }

        if ((sPenFlags & Utils.FLAG_ERASER) == Utils.FLAG_ERASER) {
            if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
                Log.d(TAG, "Eraser option is provided by default, is not configurable in Popup");
            }
            sPenFlags = sPenFlags & ~Utils.FLAG_ERASER;

        }

        if ((sPenFlags & Utils.FLAG_UNDO_REDO) == Utils.FLAG_UNDO_REDO) {
            if (Log.isLoggable(Utils.SPEN, Log.DEBUG)) {
                Log.d(TAG, "Undo Redo option is provided by default, is not configurable in Popup");
            }
            sPenFlags = sPenFlags & ~Utils.FLAG_UNDO_REDO;

        }
    } else {
        SpenException.sendPluginResult(SpenExceptionType.INVALID_SURFACE_TYPE, callbackContext);
        return null;
    }

    if ((sPenFlags & Utils.FLAG_TEXT_RECOGNITION) == Utils.FLAG_TEXT_RECOGNITION
            || (sPenFlags & Utils.FLAG_SHAPE_RECOGNITION) == Utils.FLAG_SHAPE_RECOGNITION) {
        sPenFlags = sPenFlags | Utils.FLAG_SELECTION;
    }

    SpenTrayBarOptions options = new SpenTrayBarOptions(sPenFlags);
    options.setId(id);
    options.setIsfeatureEnabled(mSpenState == SPEN_AND_HAND_SUPPORTED ? true : false);
    options.setColor(backgroundColor);
    options.setBgImageScaleType(bgImageScaleType);
    options.setImageUriScaleType(imageUriScaleType);
    options.setReturnType(returnType);
    options.setSurfaceType(surfaceType);
    options.setImagePath(imagePath);
    options.setDensity(mActivity.getApplicationContext().getResources().getDisplayMetrics().density);

    if (surfaceType == Utils.SURFACE_INLINE) {
        long xRect = 0, yRect = 0, width = 0, height = 0, xBodyRect = 0, yBodyRect = 0;
        if (args.isNull(RECTANGLE_X_VALUE) || args.isNull(RECTANGLE_Y_VALUE) || args.isNull(WIDTH)
                || args.isNull(HEIGHT)) {
            SpenException.sendPluginResult(SpenExceptionType.INVALID_INLINE_CORDINATES, callbackContext);
            return null;
        } else {
            xRect = args.optLong(RECTANGLE_X_VALUE, Integer.MIN_VALUE);
            yRect = args.optLong(RECTANGLE_Y_VALUE, Integer.MIN_VALUE);
            width = args.optLong(WIDTH, Integer.MIN_VALUE);
            height = args.optLong(HEIGHT, Integer.MIN_VALUE);
            xBodyRect = args.optLong(BODY_RECTANGLE_X_VALUE, Integer.MIN_VALUE);
            yBodyRect = args.optLong(BODY_RECTANGLE_Y_VALUE, Integer.MAX_VALUE);
            if (xRect == Integer.MIN_VALUE || yRect == Integer.MIN_VALUE || width == Integer.MIN_VALUE
                    || height == Integer.MIN_VALUE || xBodyRect == Integer.MIN_VALUE
                    || yBodyRect == Integer.MIN_VALUE || xRect > (long) Integer.MAX_VALUE
                    || yRect > (long) Integer.MAX_VALUE || width > (long) Integer.MAX_VALUE
                    || height > (long) Integer.MAX_VALUE || xBodyRect > (long) Integer.MAX_VALUE
                    || yBodyRect > (long) Integer.MAX_VALUE) {
                SpenException.sendPluginResult(SpenExceptionType.INVALID_INLINE_CORDINATES, callbackContext);
                return null;
            }
        }
        SurfacePosition surfacePosition = new SurfacePosition(mActivity.getApplicationContext(), (int) width,
                (int) height, (int) xRect - (int) xBodyRect, (int) yRect - (int) yBodyRect);
        if (!surfacePosition.isSurfaceValid(options, mActivity.getApplicationContext())) {
            SpenException.sendPluginResult(SpenExceptionType.INVALID_INLINE_CORDINATES, callbackContext);
            return null;
        }
        options.setSurfacePosition(surfacePosition);
    } else if (surfaceType == Utils.SURFACE_POPUP) {
        long popupWidth = 0, popupHeight = 0;
        popupWidth = args.optLong(POPUP_WIDTH, Integer.MIN_VALUE);
        popupHeight = args.optLong(POPUP_HEIGHT, Integer.MIN_VALUE);
        SurfacePosition surfacePosition = new SurfacePosition(mActivity.getApplicationContext(),
                (int) popupWidth, (int) popupHeight);
        options.setSurfacePosition(surfacePosition);
    }
    return options;
}