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.example.wcl.test_weiboshare.Status.java

public static Status parse(JSONObject jsonObject) {
    if (null == jsonObject) {
        return null;
    }/*from   w w w.  j a  v a  2s  .  c om*/

    Status status = new Status();
    status.created_at = jsonObject.optString("created_at");
    status.id = jsonObject.optString("id");
    status.mid = jsonObject.optString("mid");
    status.idstr = jsonObject.optString("idstr");
    status.text = jsonObject.optString("text");
    status.source = jsonObject.optString("source");
    status.favorited = jsonObject.optBoolean("favorited", false);
    status.truncated = jsonObject.optBoolean("truncated", false);

    // Have NOT supported
    status.in_reply_to_status_id = jsonObject.optString("in_reply_to_status_id");
    status.in_reply_to_user_id = jsonObject.optString("in_reply_to_user_id");
    status.in_reply_to_screen_name = jsonObject.optString("in_reply_to_screen_name");

    status.thumbnail_pic = jsonObject.optString("thumbnail_pic");
    status.bmiddle_pic = jsonObject.optString("bmiddle_pic");
    status.original_pic = jsonObject.optString("original_pic");
    status.geo = Geo.parse(jsonObject.optJSONObject("geo"));
    status.user = User.parse(jsonObject.optJSONObject("user"));
    status.retweeted_status = Status.parse(jsonObject.optJSONObject("retweeted_status"));
    status.reposts_count = jsonObject.optInt("reposts_count");
    status.comments_count = jsonObject.optInt("comments_count");
    status.attitudes_count = jsonObject.optInt("attitudes_count");
    status.mlevel = jsonObject.optInt("mlevel", -1); // Have NOT supported
    status.visible = Visible.parse(jsonObject.optJSONObject("visible"));

    JSONArray picUrlsArray = jsonObject.optJSONArray("pic_urls");
    if (picUrlsArray != null && picUrlsArray.length() > 0) {
        int length = picUrlsArray.length();
        status.pic_urls = new ArrayList<String>(length);
        JSONObject tmpObject = null;
        for (int ix = 0; ix < length; ix++) {
            tmpObject = picUrlsArray.optJSONObject(ix);
            if (tmpObject != null) {
                status.pic_urls.add(tmpObject.optString("thumbnail_pic"));
            }
        }
    }

    //status.ad = jsonObject.optString("ad", "");

    return status;
}

From source file:com.samsung.richnotification.RichNotificationHelper.java

public static List<SrnAction> createActions(Context mContext, CallbackContext callbackContext,
        RichNotificationOptions options) throws JSONException {
    ArrayList<SrnAction> actionsList = new ArrayList<SrnAction>();
    JSONArray actions = options.actions;
    if (actions == null)
        return null;

    SrnAction action = null;/*from   www.  j a  v  a  2  s .co  m*/
    for (int i = 0; i < actions.length(); i++) {
        JSONObject act = actions.optJSONObject(i);
        if (act == null)
            continue;

        String actionLabel = act.optString("actionLabel", EMPTY_STRING);
        if (actionLabel.isEmpty())
            continue;

        Bitmap actionIcon = getIconBitmap(mContext, "file://" + act.optString("actionIcon"));
        SrnImageAsset actionImg = new SrnImageAsset(mContext, actionLabel, actionIcon);

        int actionType = act.optInt("type");
        switch (actionType) {

        case ACTION_TYPE_CALL:
            SrnRemoteBuiltInAction call = new SrnRemoteBuiltInAction(actionLabel, OperationType.CALL);
            call.setData(Uri.parse(act.optString("dest")));
            action = call;
            break;
        case ACTION_TYPE_SMS:
            SrnRemoteBuiltInAction sms = new SrnRemoteBuiltInAction(actionLabel, OperationType.SMS);
            sms.setData(Uri.fromParts("sms", act.optString("dest"), null));
            action = sms;
            break;
        case ACTION_TYPE_EMAIL:
            Log.d(TAG, "Email to: '" + act.optString("dest") + "'");
            Log.d(TAG, "Subject: '" + act.optString("subject") + "'");
            Log.d(TAG, "Body: '" + act.optString("body") + "'");

            SrnHostAction email = new SrnHostAction(actionLabel);
            Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
            String uriText = "mailto:" + act.optString("dest") + "?subject="
                    + Uri.encode(act.optString("subject")) + "&body=" + Uri.encode(act.optString("body"));
            Uri uri = Uri.parse(uriText);
            emailIntent.setData(uri);
            email.setCallbackIntent(CallbackIntent.getActivityCallback(emailIntent));
            email.setToast(act.optString("toast"));
            email.setIcon(actionImg);
            action = email;
            break;
        case ACTION_TYPE_VIEW:
            SrnHostAction view = new SrnHostAction(actionLabel);
            Intent viewIntent = new Intent(Intent.ACTION_VIEW);
            String urlText = act.optString("dest");
            Uri url = Uri.parse(urlText);
            viewIntent.setData(url);
            view.setCallbackIntent(CallbackIntent.getActivityCallback(viewIntent));
            view.setToast(act.optString("toast"));
            view.setIcon(actionImg);
            action = view;
            break;
        case ACTION_TYPE_INPUT_KEYBOARD:
        case ACTION_TYPE_INPUT_SINGLE_SELECT:
        case ACTION_TYPE_INPUT_MULTI_SELECT:
            SrnRemoteInputAction input = getRemoteInputAction(mContext, act);
            if (input == null) {
                continue;
            }

            Intent inputIntent = new Intent("com.samsung.cordova.richnotification.remote_input_receiver");
            inputIntent.putExtra("callbackID", callbackContext.getCallbackId());
            String actionID = act.optString("actionID", EMPTY_STRING);
            if (actionID.isEmpty()) {
                continue;
            } else {
                inputIntent.putExtra("actionID", actionID);
            }
            input.setCallbackIntent(CallbackIntent.getBroadcastCallback(inputIntent));
            input.setIcon(actionImg);
            action = input;
            break;
        default:
            Log.e(TAG, "Invalid action type: " + actionType);
            continue;
        }

        Log.d(TAG, "Action type created: " + actionType);
        actionsList.add(action);
    }

    return actionsList;
}

From source file:com.samsung.richnotification.RichNotificationHelper.java

private static SrnRemoteInputAction getRemoteInputAction(Context mContext, JSONObject action)
        throws JSONException {
    SrnRemoteInputAction inputAction = null;
    String actionLabel = action.optString("actionLabel");
    if (actionLabel == null || actionLabel.isEmpty())
        return null;

    inputAction = new SrnRemoteInputAction(actionLabel);

    int inputType = action.optInt("type");
    switch (inputType) {
    case ACTION_TYPE_INPUT_KEYBOARD:
        KeyboardInputMode kbInput = InputModeFactory.createKeyboardInputMode();
        String prefillString = action.optString("body");
        int charLimit = action.optInt("charLimit", 0);
        if (charLimit > 0 && charLimit <= prefillString.length()) {
            kbInput.setCharacterLimit(charLimit);
            kbInput.setPrefillString(prefillString.substring(0, charLimit));
        } else if (charLimit > 0 && charLimit > prefillString.length()) {
            kbInput.setCharacterLimit(charLimit);
            kbInput.setPrefillString(prefillString);
        } else {//from  w  w  w  .j  a va 2  s.c om
            kbInput.setPrefillString(prefillString);
        }
        int keyboardType = action.optInt("keyboardType", KEYBOARD_NORMAL);
        kbInput.setKeyboardType(getKeyboardType(keyboardType));
        inputAction.setRequestedInputMode(kbInput);
        break;
    case ACTION_TYPE_INPUT_SINGLE_SELECT:
    case ACTION_TYPE_INPUT_MULTI_SELECT:
        SingleSelectInputMode single = InputModeFactory.createSingleSelectInputMode();
        MultiSelectInputMode multi = InputModeFactory.createMultiSelectInputMode();
        JSONArray choices = action.optJSONArray("choices");
        Log.d(TAG, "Choices: " + choices);
        if (choices == null || choices.length() == 0)
            return null;

        for (int index = 0; index < choices.length(); index++) {
            JSONObject choice = choices.optJSONObject(index);
            Log.d(TAG, "Choice: " + choice);
            if (choice == null)
                continue;

            String choiceLabel = choice.optString("choiceLabel", null);
            String choiceID = choice.optString("choiceID", null);
            if (choiceLabel == null || choiceID == null)
                continue;

            Bitmap chIco = getIconBitmap(mContext, "file://" + choice.optString("choiceIcon"));
            Log.d(TAG, "chIco for '" + choiceLabel + "'' : " + chIco);
            SrnImageAsset choiceImg = new SrnImageAsset(mContext, choiceLabel, chIco);

            boolean selected = choice.optBoolean("selected");
            if (inputType == ACTION_TYPE_INPUT_SINGLE_SELECT) {
                single.addChoice(choiceLabel, choiceID, choiceImg);
                inputAction.setRequestedInputMode(single);
            } else {
                multi.addChoice(choiceLabel, choiceID, choiceImg, selected);
                inputAction.setRequestedInputMode(multi);
            }
        }

        break;
    default:
        Log.d(TAG, "Invalid input type. Hence, ignoring.");
        return null;
    }
    return inputAction;
}

From source file:com.danlvse.weebo.model.Favorite.java

public static Favorite parse(JSONObject jsonObject) {
    if (null == jsonObject) {
        return null;
    }//from   w w  w  . j a v  a2s . co m

    Favorite favorite = new Favorite();
    favorite.status = Feed.parse(jsonObject.optJSONObject("status"));
    favorite.favorited_time = jsonObject.optString("favorited_time");

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

    return favorite;
}

From source file:me.calebjones.blogsite.network.PostDownloader.java

private void getPostAll() {

    //Setup the URLS that I will need
    String firstUrl = "https://public-api.wordpress.com/rest/v1.1/sites/calebjones.me/posts/"
            + "?pretty=true&number=100&fields=ID,title&order_by=ID";
    String nextPage = "https://public-api.wordpress.com/rest/v1.1/sites/calebjones.me/posts/"
            + "?pretty=true&number=100&fields=ID,title&order_by=ID&page_handle=";

    Request request = new Request.Builder().url(firstUrl).build();

    int count = 0;

    try {/*  w ww  .j av a 2s  . c  o m*/

        //First make a call to see how many total posts there are and save to 'found'
        final Response response = BlogsiteApplication.getInstance().client.newCall(request).execute();
        if (!response.isSuccessful()) {
            mBuilder.setContentText("Download failed.").setProgress(0, 0, false).setAutoCancel(true)
                    .setOngoing(false);
            mNotifyManager.notify(NOTIF_ID, mBuilder.build());
            throw new IOException();
        } else {

            //Take the response and parse the JSON
            JSONObject JObject = new JSONObject(response.body().string());
            JSONArray posts = JObject.optJSONArray("posts");

            //Store the data into the two objects, meta gets the next page later on.
            // Found is total post count.
            String meta = JObject.optString("meta");
            int found = JObject.optInt("found");

            postID = new ArrayList<>();

            //If there are more then 100, which there always will unless something
            // catastrophic happens then set up the newURL.
            if (found > 100) {
                JSONObject metaLink = new JSONObject(meta);
                String nextValue = metaLink.optString("next_page");
                newURL = nextPage + URLEncoder.encode(nextValue, "UTF-8");
                Log.d("The Jones Theory", newURL);
            }

            // Loop through the posts and add the post ID to the array.
            // The posts is still from the original call.
            for (int i = 0; i < posts.length(); i++) {
                JSONObject post = posts.optJSONObject(i);
                postID.add(post.optString("ID"));
                count++;
            }

            //Now this logic is in charge of loading the next pages
            // until all posts are loaded into the array.
            while (count != found) {
                Request newRequest = new Request.Builder().url(newURL).build();
                Response newResponse = BlogsiteApplication.getInstance().client.newCall(newRequest).execute();
                if (!newResponse.isSuccessful())
                    throw new IOException();

                JSONObject nJObject = new JSONObject(newResponse.body().string());
                JSONArray nPosts = nJObject.optJSONArray("posts");
                String nMeta = nJObject.optString("meta");
                int newFound = nJObject.optInt("found");

                if (newFound > 100) {
                    JSONObject metaLink = new JSONObject(nMeta);
                    String nextValue = metaLink.optString("next_page");
                    newURL = nextPage + URLEncoder.encode(nextValue, "UTF-8");
                }
                for (int i = 0; i < nPosts.length(); i++) {
                    JSONObject post = nPosts.optJSONObject(i);
                    postID.add(post.optString("ID"));
                    count++;
                }
            }
            Collections.reverse(postID);
            download(postID);
            Log.d("The Jones Theory",
                    "getPostAll - Downloading = " + SharedPrefs.getInstance().isDownloading());
        }
    } catch (IOException | JSONException e) {
        if (SharedPrefs.getInstance().isFirstDownload()) {
            SharedPrefs.getInstance().setFirstDownload(false);
        }
        SharedPrefs.getInstance().setDownloading(false);
        e.printStackTrace();
    }
}

From source file:me.calebjones.blogsite.network.PostDownloader.java

private void getPostMissing() {
    notificationService();//from w w  w. j  a va  2 s.  c om
    SharedPrefs.getInstance().setDownloading(true);
    DatabaseManager databaseManager = new DatabaseManager(this);
    //Setup the URLS that I will need
    String firstUrl = "https://public-api.wordpress.com/rest/v1.1/sites/calebjones.me/posts/"
            + "?pretty=true&number=100&fields=ID,title&order_by=ID";
    String nextPage = "https://public-api.wordpress.com/rest/v1.1/sites/calebjones.me/posts/"
            + "?pretty=true&number=100&fields=ID,title&order_by=ID&page_handle=";
    Request request = new Request.Builder().url(firstUrl).build();
    int count = 0;

    try {

        //First make a call to see how many total posts there are and save to 'found'
        final Response response = BlogsiteApplication.getInstance().client.newCall(request).execute();
        if (!response.isSuccessful())
            throw new IOException();

        //Take the response and parse the JSON
        JSONObject JObject = new JSONObject(response.body().string());
        JSONArray posts = JObject.optJSONArray("posts");

        //Store the data into the two objects, meta gets the next page later on.
        // Found is total post count.
        String meta = JObject.optString("meta");
        int found = JObject.optInt("found");

        postID = new ArrayList<>();

        //If there are more then 100, which there always will unless something
        // catastrophic happens then set up the newURL.
        if (found > 100) {
            JSONObject metaLink = new JSONObject(meta);
            String nextValue = metaLink.optString("next_page");
            newURL = nextPage + URLEncoder.encode(nextValue, "UTF-8");
        }

        // Loop through the posts and add the post ID to the array.
        // The posts is still from the original call.
        for (int i = 0; i < posts.length(); i++) {
            JSONObject post = posts.optJSONObject(i);
            if (!databaseManager.idExists(post.optString("ID"))) {
                postID.add(post.optString("ID"));
            }
            count++;
        }

        //Now this logic is in charge of loading the next pages
        // until all posts are loaded into the array.
        while (count != found) {
            Request newRequest = new Request.Builder().url(newURL).build();
            Response newResponse = BlogsiteApplication.getInstance().client.newCall(newRequest).execute();
            if (!newResponse.isSuccessful())
                throw new IOException();

            JSONObject nJObject = new JSONObject(newResponse.body().string());
            JSONArray nPosts = nJObject.optJSONArray("posts");
            String nMeta = nJObject.optString("meta");
            int newFound = nJObject.optInt("found");

            if (newFound > 100) {
                JSONObject metaLink = new JSONObject(nMeta);
                String nextValue = metaLink.optString("next_page");
                newURL = nextPage + URLEncoder.encode(nextValue, "UTF-8");

            }

            for (int i = 0; i < nPosts.length(); i++) {
                JSONObject post = nPosts.optJSONObject(i);
                if (!databaseManager.idExists(post.optString("ID"))) {
                    postID.add(post.optString("ID"));
                }
                count++;
            }
        }
    } catch (IOException | JSONException e) {
        if (SharedPrefs.getInstance().isFirstDownload()) {
            SharedPrefs.getInstance().setFirstDownload(false);
        }
        SharedPrefs.getInstance().setDownloading(false);
        e.printStackTrace();
    }
    Collections.reverse(postID);
    download(postID);
}

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

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

    GroupList groupList = new GroupList();
    try {
        JSONObject jsonObject = new JSONObject(jsonString);
        groupList.total_number = jsonObject.optInt("total_number");

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

    return groupList;
}

From source file:at.alladin.rmbt.android.views.ResultGraphView.java

/**
 * //from  w  w  w  . j a v a 2s  .  c o m
 * @param graphArray
 * @param graphView
 * @throws JSONException
 */
public void drawCurve(JSONArray graphArray, CustomizableGraphView graphView, String color, String labelHMax)
        throws JSONException {
    final double maxTime = graphArray.optJSONObject(graphArray.length() - 1).optDouble("time_elapsed");
    //final double pointDistance = (0.25d / (maxTime / 1000));

    graphView.getLabelHMaxList().clear();
    graphView.addLabelHMax(labelHMax);

    //StaticGraph signal = StaticGraph.addGraph(graphView, Color.parseColor(color));
    GraphService signal = SmoothGraph.addGraph(graphView, Color.parseColor(color),
            RMBTTestFragment.SMOOTHING_DATA_AMOUNT, RMBTTestFragment.SMOOTHING_FUNCTION, false);

    if (graphArray != null && graphArray.length() > 0) {
        long bytes = 0;
        for (int i = 0; i < graphArray.length(); i++) {
            JSONObject uploadObject = graphArray.getJSONObject(i);
            double time_elapsed = uploadObject.getInt("time_elapsed");
            bytes = uploadObject.getInt("bytes_total");
            double bitPerSec = (bytes * 8000 / time_elapsed);
            double time = (time_elapsed / maxTime);

            if (i + 1 == graphArray.length()) {
                signal.addValue(IntermediateResult.toLog((long) bitPerSec), time, SmoothGraph.FLAG_ALIGN_RIGHT);
            } else {
                signal.addValue(IntermediateResult.toLog((long) bitPerSec), time,
                        i == 0 ? SmoothGraph.FLAG_ALIGN_LEFT : SmoothGraph.FLAG_NONE);
            }
        }
    }
}

From source file:com.phonegap.Capture.java

@Override
public PluginResult execute(String action, JSONArray args, String callbackId) {
    this.callbackId = callbackId;
    this.limit = 1;
    this.duration = 0.0f;
    this.results = new JSONArray();

    JSONObject options = args.optJSONObject(0);
    if (options != null) {
        limit = options.optLong("limit", 1);
        duration = options.optDouble("duration", 0.0f);
    }/*from ww  w. j  av a  2s . co  m*/

    if (action.equals("getFormatData")) {
        try {
            JSONObject obj = getFormatData(args.getString(0), args.getString(1));
            return new PluginResult(PluginResult.Status.OK, obj);
        } catch (JSONException e) {
            return new PluginResult(PluginResult.Status.ERROR);
        }
    } else if (action.equals("captureAudio")) {
        this.captureAudio();
    } else if (action.equals("captureImage")) {
        this.captureImage();
    } else if (action.equals("captureVideo")) {
        this.captureVideo(duration);
    }

    PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
    r.setKeepCallback(true);
    return r;
}

From source file:com.app.plugins.childBrowser.ChildBrowser.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 ww .j  a  va2 s  .  com*/
public PluginResult execute(String action, JSONArray args, String callbackId) {
    PluginResult.Status status = PluginResult.Status.OK;
    String result = "";

    try {
        if (action.equals("showWebPage")) {
            this.browserCallbackId = callbackId;

            // If the ChildBrowser is already open then throw an error
            if (dialog != null && dialog.isShowing()) {
                return new PluginResult(PluginResult.Status.ERROR, "ChildBrowser is already open");
            }

            result = this.showWebPage(args.getString(0), args.optJSONObject(1));

            if (result.length() > 0) {
                status = PluginResult.Status.ERROR;
                return new PluginResult(status, result);
            } else {
                PluginResult pluginResult = new PluginResult(status, result);
                pluginResult.setKeepCallback(true);
                return pluginResult;
            }
        } else if (action.equals("close")) {
            closeDialog();

            JSONObject obj = new JSONObject();
            obj.put("type", CLOSE_EVENT);

            this.onClose();

            PluginResult pluginResult = new PluginResult(status, obj);
            pluginResult.setKeepCallback(false);
            return pluginResult;
        } else if (action.equals("openExternal")) {
            result = this.openExternal(args.getString(0), args.optBoolean(1));
            if (result.length() > 0) {
                status = PluginResult.Status.ERROR;
            }
        } else {
            status = PluginResult.Status.INVALID_ACTION;
        }
        return new PluginResult(status, result);
    } catch (JSONException e) {
        return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
    }
}