Example usage for org.json JSONObject optJSONArray

List of usage examples for org.json JSONObject optJSONArray

Introduction

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

Prototype

public JSONArray optJSONArray(String key) 

Source Link

Document

Get an optional JSONArray associated with a key.

Usage

From source file:com.wlcg.aroundme.cc.weather.YahooWeatherProvider.java

@Override
public List<LocationResult> getLocations(String input) {
    String language = getLanguage();
    String params = "\"" + input + "\" and lang = \"" + language + "\"";
    String url = URL_LOCATION + Uri.encode(params);
    JSONObject jsonResults = fetchResults(url);
    if (jsonResults == null) {
        return null;
    }//from  w  ww .j a v  a2 s  . c om

    try {
        JSONArray places = jsonResults.optJSONArray("place");
        if (places == null) {
            // Yahoo returns an object instead of an array when there's only one result
            places = new JSONArray();
            places.put(jsonResults.getJSONObject("place"));
        }

        ArrayList<LocationResult> results = new ArrayList<LocationResult>();
        for (int i = 0; i < places.length(); i++) {
            LocationResult result = parsePlace(places.getJSONObject(i));
            if (result != null) {
                results.add(result);
            }
        }
        return results;
    } catch (JSONException e) {
        Log.e(TAG, "Received malformed places data (input=" + input + ", lang=" + language + ")", e);
    }
    return null;
}

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

/**
 * Fills a Poll instance from JSONObject.
 *///from ww  w .j  ava  2  s .  c  o  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.catnut.fragment.MyRelationshipFragment.java

@Override
protected void refresh() {
    // ???/*from w  w w  .ja v  a  2s.c o  m*/
    if (!isNetworkAvailable()) {
        Toast.makeText(getActivity(), getString(R.string.network_unavailable), Toast.LENGTH_SHORT).show();
        initFromLocal();
        return;
    }
    // refresh!
    CatnutAPI api = mIsFollowing ? FriendshipsAPI.friends(mUid, getFetchSize(), 0, 1)
            : FriendshipsAPI.followers(mUid, getFetchSize(), 0, 1);
    mRequestQueue.add(new CatnutRequest(getActivity(), api, new UserProcessor.UsersProcessor(),
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "refresh done...");
                    mTotal = response.optInt(TOTAL_NUMBER);
                    mNextCursor = response.optInt(NEXT_CURSOR);
                    // ???
                    mLastTotalNumber = 0;
                    JSONArray jsonArray = response.optJSONArray(User.MULTIPLE);
                    int newSize = jsonArray.length(); // ...
                    Bundle args = new Bundle();
                    args.putInt(TAG, newSize);
                    getLoaderManager().restartLoader(0, args, MyRelationshipFragment.this);
                }
            }, errorListener)).setTag(TAG);
}

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

private void loadFromCloud(long max_id) {
    mSwipeRefreshLayout.setRefreshing(true);
    CatnutAPI api = mIsFollowing ? FriendshipsAPI.friends(mUid, getFetchSize(), mNextCursor, 1)
            : FriendshipsAPI.followers(mUid, getFetchSize(), mNextCursor, 1);
    mRequestQueue.add(new CatnutRequest(getActivity(), api, new UserProcessor.UsersProcessor(),
            new Response.Listener<JSONObject>() {
                @Override//w ww.  j  ava2s  .  c  o  m
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "load more from cloud done...");
                    mTotal = response.optInt(TOTAL_NUMBER);
                    mNextCursor = response.optInt(NEXT_CURSOR);
                    mLastTotalNumber = mAdapter.getCount();
                    int newSize = response.optJSONArray(User.MULTIPLE).length() + mAdapter.getCount();
                    Bundle args = new Bundle();
                    args.putInt(TAG, newSize);
                    getLoaderManager().restartLoader(0, args, MyRelationshipFragment.this);
                }
            }, errorListener)).setTag(TAG);
}

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  ww  w  . j a  v a 2  s  .c o m*/
    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//  www . j a  v a 2 s.  c  o 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:com.vk.sdkweb.api.model.VKApiPhotoAlbum.java

/**
 * Creates a PhotoAlbum instance from JSONObject.
 */// w w w  .j  a  va  2 s .  co m
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.hichinaschool.flashcards.libanki.Sched.java

private JSONObject _newConf(Card card) {
    try {//from w  w w. j av a  2  s.c  o m
        JSONObject conf = _cardConf(card);
        // normal deck
        if (card.getODid() == 0) {
            return conf.getJSONObject("new");
        }
        // dynamic deck; override some attributes, use original deck for others
        JSONObject oconf = mCol.getDecks().confForDid(card.getODid());
        JSONArray delays = conf.optJSONArray("delays");
        if (delays == null) {
            delays = oconf.getJSONObject("new").getJSONArray("delays");
        }
        JSONObject dict = new JSONObject();
        // original deck
        dict.put("ints", oconf.getJSONObject("new").getJSONArray("ints"));
        dict.put("initialFactor", oconf.getJSONObject("new").getInt("initialFactor"));
        dict.put("bury", oconf.getJSONObject("new").optBoolean("bury", true));
        // overrides
        dict.put("delays", delays);
        dict.put("separate", conf.getBoolean("separate"));
        dict.put("order", NEW_CARDS_DUE);
        dict.put("perDay", mReportLimit);
        return dict;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.hichinaschool.flashcards.libanki.Sched.java

private JSONObject _lapseConf(Card card) {
    try {//from  w ww  . java  2  s. c om
        JSONObject conf = _cardConf(card);
        // normal deck
        if (card.getODid() == 0) {
            return conf.getJSONObject("lapse");
        }
        // dynamic deck; override some attributes, use original deck for others
        JSONObject oconf = mCol.getDecks().confForDid(card.getODid());
        JSONArray delays = conf.optJSONArray("delays");
        if (delays == null) {
            delays = oconf.getJSONObject("lapse").getJSONArray("delays");
        }
        JSONObject dict = new JSONObject();
        // original deck
        dict.put("minInt", oconf.getJSONObject("lapse").getInt("minInt"));
        dict.put("leechFails", oconf.getJSONObject("lapse").getInt("leechFails"));
        dict.put("leechAction", oconf.getJSONObject("lapse").getInt("leechAction"));
        dict.put("mult", oconf.getJSONObject("lapse").getDouble("mult"));
        // overrides
        dict.put("delays", delays);
        dict.put("resched", conf.getBoolean("resched"));
        return dict;
    } catch (JSONException e) {
        if (!mCol.getDecks().isDyn(card.getDid()) && card.getODid() != 0) {
            // workaround, if a card's deck is a normal deck, but odid != 0
            card.setODue(0);
            card.setODid(0);
            AnkiDroidApp.saveExceptionReportFile(e, "fixedODidInconsistencyInSched_lapseConf");
            // return proper value after having fixed the problem
            return _lapseConf(card);
        } else {
            throw new RuntimeException(e);
        }
    }
}

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  ww w .j ava  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;
}