Example usage for org.json JSONObject optString

List of usage examples for org.json JSONObject optString

Introduction

In this page you can find the example usage for org.json JSONObject optString.

Prototype

public String optString(String key) 

Source Link

Document

Get an optional string associated with a key.

Usage

From source file:curt.android.result.supplement.BookResultInfoRetriever.java

@Override
void retrieveSupplementalInfo() throws IOException, InterruptedException {

    String contents = HttpHelper.downloadViaHttp("https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn,
            HttpHelper.ContentType.JSON);

    if (contents.length() == 0) {
        return;/*  w  w  w.  java 2  s  .c  o m*/
    }

    String title;
    String pages;
    Collection<String> authors = null;

    try {

        JSONObject topLevel = (JSONObject) new JSONTokener(contents).nextValue();
        JSONArray items = topLevel.optJSONArray("items");
        if (items == null || items.isNull(0)) {
            return;
        }

        JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo");
        if (volumeInfo == null) {
            return;
        }

        title = volumeInfo.optString("title");
        pages = volumeInfo.optString("pageCount");

        JSONArray authorsArray = volumeInfo.optJSONArray("authors");
        if (authorsArray != null && !authorsArray.isNull(0)) {
            authors = new ArrayList<String>();
            for (int i = 0; i < authorsArray.length(); i++) {
                authors.add(authorsArray.getString(i));
            }
        }

    } catch (JSONException e) {
        throw new IOException(e.toString());
    }

    Collection<String> newTexts = new ArrayList<String>();

    if (title != null && title.length() > 0) {
        newTexts.add(title);
    }

    if (authors != null && !authors.isEmpty()) {
        boolean first = true;
        StringBuilder authorsText = new StringBuilder();
        for (String author : authors) {
            if (first) {
                first = false;
            } else {
                authorsText.append(", ");
            }
            authorsText.append(author);
        }
        newTexts.add(authorsText.toString());
    }

    if (pages != null && pages.length() > 0) {
        newTexts.add(pages + "pp.");
    }

    String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context)
            + "/search?tbm=bks&source=zxing&q=";

    append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn);
}

From source file:com.linkedin.platform.errors.ApiErrorResponse.java

public static ApiErrorResponse build(JSONObject jsonErr) throws JSONException {
    return new ApiErrorResponse(jsonErr, jsonErr.optInt(ERROR_CODE, -1), jsonErr.optString(MESSAGE),
            jsonErr.optString(REQUEST_ID), jsonErr.optInt(STATUS, -1), jsonErr.optLong(TIMESTAMP, 0));
}

From source file:com.vk.sdkweb.api.model.VKApiPoll.java

/**
 * Fills a Poll instance from JSONObject.
 *//*w  ww.j  a  v a2s  .co  m*/
public VKApiPoll parse(JSONObject source) {
    id = source.optInt("id");
    owner_id = source.optInt("owner_id");
    created = source.optLong("created");
    question = source.optString("question");
    votes = source.optInt("votes");
    answer_id = source.optInt("answer_id");
    answers = new VKList<Answer>(source.optJSONArray("answers"), Answer.class);
    return this;
}

From source file:org.chromium.ChromeNotifications.java

private void makeNotification(final CordovaArgs args) throws JSONException {
    String notificationId = args.getString(0);
    JSONObject options = args.getJSONObject(1);
    Resources resources = cordova.getActivity().getResources();
    Bitmap largeIcon = makeBitmap(options.getString("iconUrl"),
            resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_width),
            resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_height));
    int smallIconId = resources.getIdentifier("notification_icon", "drawable",
            cordova.getActivity().getPackageName());
    if (smallIconId == 0) {
        smallIconId = resources.getIdentifier("icon", "drawable", cordova.getActivity().getPackageName());
    }/*from  w ww . ja v  a  2  s . c  om*/
    NotificationCompat.Builder builder = new NotificationCompat.Builder(cordova.getActivity())
            .setSmallIcon(smallIconId).setContentTitle(options.getString("title"))
            .setContentText(options.getString("message")).setLargeIcon(largeIcon)
            .setPriority(options.optInt("priority"))
            .setContentIntent(makePendingIntent(NOTIFICATION_CLICKED_ACTION, notificationId, -1,
                    PendingIntent.FLAG_CANCEL_CURRENT))
            .setDeleteIntent(makePendingIntent(NOTIFICATION_CLOSED_ACTION, notificationId, -1,
                    PendingIntent.FLAG_CANCEL_CURRENT));
    double eventTime = options.optDouble("eventTime");
    if (eventTime != 0) {
        builder.setWhen(Math.round(eventTime));
    }
    JSONArray buttons = options.optJSONArray("buttons");
    if (buttons != null) {
        for (int i = 0; i < buttons.length(); i++) {
            JSONObject button = buttons.getJSONObject(i);
            builder.addAction(android.R.drawable.ic_dialog_info, button.getString("title"), makePendingIntent(
                    NOTIFICATION_BUTTON_CLICKED_ACTION, notificationId, i, PendingIntent.FLAG_CANCEL_CURRENT));
        }
    }
    String type = options.getString("type");
    Notification notification;
    if ("image".equals(type)) {
        NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle(builder);
        String bigImageUrl = options.optString("imageUrl");
        if (!bigImageUrl.isEmpty()) {
            bigPictureStyle.bigPicture(makeBitmap(bigImageUrl, 0, 0));
        }
        notification = bigPictureStyle.build();
    } else if ("list".equals(type)) {
        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(builder);
        JSONArray items = options.optJSONArray("items");
        if (items != null) {
            for (int i = 0; i < items.length(); i++) {
                JSONObject item = items.getJSONObject(i);
                inboxStyle.addLine(Html.fromHtml("<b>" + item.getString("title")
                        + "</b>&nbsp;&nbsp;&nbsp;&nbsp;" + item.getString("message")));
            }
        }
        notification = inboxStyle.build();
    } else {
        if ("progress".equals(type)) {
            int progress = options.optInt("progress");
            builder.setProgress(100, progress, false);
        }
        NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle(builder);
        bigTextStyle.bigText(options.getString("message"));
        notification = bigTextStyle.build();
    }
    notificationManager.notify(notificationId.hashCode(), notification);
}

From source file:com.facebook.login.LoginClient.java

/**
 * This parses a server response to a call to me/permissions.  It will return the list of
 * granted permissions. It will optionally update an access token with the requested permissions.
 *
 * @param response The server response//  w w  w  .  ja va  2s.co  m
 * @return A list of granted permissions or null if an error
 */
private static PermissionsPair handlePermissionResponse(GraphResponse response) {
    if (response.getError() != null) {
        return null;
    }

    JSONObject result = response.getJSONObject();
    if (result == null) {
        return null;
    }

    JSONArray data = result.optJSONArray("data");
    if (data == null || data.length() == 0) {
        return null;
    }
    List<String> grantedPermissions = new ArrayList<String>(data.length());
    List<String> declinedPermissions = new ArrayList<String>(data.length());

    for (int i = 0; i < data.length(); ++i) {
        JSONObject object = data.optJSONObject(i);
        String permission = object.optString("permission");
        if (permission == null || permission.equals("installed")) {
            continue;
        }
        String status = object.optString("status");
        if (status == null) {
            continue;
        }
        if (status.equals("granted")) {
            grantedPermissions.add(permission);
        } else if (status.equals("declined")) {
            declinedPermissions.add(permission);
        }
    }

    return new PermissionsPair(grantedPermissions, declinedPermissions);
}

From source file:org.apache.cordova.plugins.barcodescanner.BarcodeScanner.java

/**
 * Executes the request and returns PluginResult.
 *
 * @param action        The action to execute.
 * @param args          JSONArray 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.
 *//*from   w  ww.j  ava  2s  . c o m*/
public PluginResult execute(String action, JSONArray args, String callbackId) {
    this.callback = callbackId;

    if (action.equals("encode")) {
        JSONObject obj = args.optJSONObject(0);
        if (obj != null) {
            String type = obj.optString("type");
            String data = obj.optString("data");

            // If the type is null then force the type to text
            if (type == null) {
                type = TEXT_TYPE;
            }

            if (data == null) {
                return new PluginResult(PluginResult.Status.ERROR, "User did not specify data to encode");
            }

            encode(type, data);
        } else {
            return new PluginResult(PluginResult.Status.ERROR, "User did not specify data to encode");
        }
    } else if (action.equals("scan")) {
        scan();
    } else {
        return new PluginResult(PluginResult.Status.INVALID_ACTION);
    }
    PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
    r.setKeepCallback(true);
    return r;
}

From source file:com.vk.sdkweb.api.model.VKApiPhotoAlbum.java

/**
 * Creates a PhotoAlbum instance from JSONObject.
 *///from   w ww  .jav  a 2s. c  om
public VKApiPhotoAlbum parse(JSONObject from) {
    id = from.optInt("id");
    thumb_id = from.optInt("thumb_id");
    owner_id = from.optInt("owner_id");
    title = from.optString("title");
    description = from.optString("description");
    created = from.optLong("created");
    updated = from.optLong("updated");
    size = from.optInt("size");
    can_upload = ParseUtils.parseBoolean(from, "can_upload");
    thumb_src = from.optString("thumb_src");
    if (from.has("privacy")) {
        privacy = from.optInt("privacy");
    } else {
        privacy = VKPrivacy.parsePrivacy(from.optJSONObject("privacy_view"));
    }
    JSONArray sizes = from.optJSONArray("sizes");
    if (sizes != null) {
        photo.fill(sizes);
    } else {
        photo.add(VKApiPhotoSize.create(COVER_S, 75, 55));
        photo.add(VKApiPhotoSize.create(COVER_M, 130, 97));
        photo.add(VKApiPhotoSize.create(COVER_X, 432, 249));
        photo.sort();
    }
    return this;
}

From source file:com.vk.sdkweb.api.model.VKApiCommunityFull.java

public VKApiCommunityFull parse(JSONObject jo) {
    super.parse(jo);

    JSONObject city = jo.optJSONObject(CITY);
    if (city != null) {
        this.city = new VKApiCity().parse(city);
    }//from   w  ww .ja va  2 s. c  o m
    JSONObject country = jo.optJSONObject(COUNTRY);
    if (country != null) {
        this.country = new VKApiCountry().parse(country);
    }

    JSONObject place = jo.optJSONObject(PLACE);
    if (place != null)
        this.place = new VKApiPlace().parse(place);

    description = jo.optString(DESCRIPTION);
    wiki_page = jo.optString(WIKI_PAGE);
    members_count = jo.optInt(MEMBERS_COUNT);

    JSONObject counters = jo.optJSONObject(COUNTERS);
    if (counters != null)
        this.counters = new Counters(place);

    start_date = jo.optLong(START_DATE);
    end_date = jo.optLong(END_DATE);
    can_post = ParseUtils.parseBoolean(jo, CAN_POST);
    can_see_all_posts = ParseUtils.parseBoolean(jo, CAN_SEE_ALL_POSTS);
    status = jo.optString(STATUS);

    JSONObject status_audio = jo.optJSONObject("status_audio");
    if (status_audio != null)
        this.status_audio = new VKApiAudio().parse(status_audio);

    contacts = new VKList<Contact>(jo.optJSONArray(CONTACTS), Contact.class);
    links = new VKList<Link>(jo.optJSONArray(LINKS), Link.class);
    fixed_post = jo.optInt(FIXED_POST);
    verified = ParseUtils.parseBoolean(jo, VERIFIED);
    blacklisted = ParseUtils.parseBoolean(jo, VERIFIED);
    site = jo.optString(SITE);
    return this;
}

From source file:org.cruxframework.crux.widgets.rebind.deviceadaptivegrid.DeviceAdaptiveGridFactory.java

protected boolean getShowRowDetailsIcon(JSONObject gridElem) {
    String showRowDetailsIcon = gridElem.optString("showRowDetailsIcon");
    if (!StringUtils.isEmpty(showRowDetailsIcon)) {
        return Boolean.parseBoolean(showRowDetailsIcon);
    } else {//from   ww w .  j av a 2  s .c o  m
        return true;
    }
}

From source file:org.cruxframework.crux.widgets.rebind.deviceadaptivegrid.DeviceAdaptiveGridFactory.java

protected boolean getFreezeHeaders(JSONObject gridElem) {
    String strFreeze = gridElem.optString("freezeHeaders");
    if (!StringUtils.isEmpty(strFreeze)) {
        return Boolean.parseBoolean(strFreeze);
    } else {/*from w w w.j  a  v  a 2 s. com*/
        return false;
    }
}