Example usage for org.json JSONObject optBoolean

List of usage examples for org.json JSONObject optBoolean

Introduction

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

Prototype

public boolean optBoolean(String key) 

Source Link

Document

Get an optional boolean associated with a key.

Usage

From source file:sh.calaba.driver.client.model.impl.ViewImpl.java

@Override
public Boolean isEnabled() {
    JSONObject result = executeCalabashCommand(CalabashCommands.GET_VIEW_PROPERTY, id.getIdentifier(),
            "enabled");
    return result.optBoolean("message");
}

From source file:com.tatsuowatanabe.funukulelequiz.util.Purchase.java

public Purchase(String itemType, String jsonPurchaseInfo, String signature) throws JSONException {
    mItemType = itemType;//from w ww  .  j  a  va2  s  .c  om
    mOriginalJson = jsonPurchaseInfo;
    JSONObject o = new JSONObject(mOriginalJson);
    mOrderId = o.optString("orderId");
    mPackageName = o.optString("packageName");
    mSku = o.optString("productId");
    mPurchaseTime = o.optLong("purchaseTime");
    mPurchaseState = o.optInt("purchaseState");
    mDeveloperPayload = o.optString("developerPayload");
    mToken = o.optString("token", o.optString("purchaseToken"));
    mIsAutoRenewing = o.optBoolean("autoRenewing");
    mSignature = signature;
}

From source file:org.catnut.metadata.User.java

@Override
public ContentValues convert(JSONObject json) {
    ContentValues user = new ContentValues();
    user.put(BaseColumns._ID, json.optLong(Constants.ID));
    user.put(screen_name, json.optString(screen_name));
    user.put(name, json.optString(name));
    user.put(province, json.optInt(province));
    user.put(city, json.optInt(city));/*from   ww  w .ja v  a2s .c o m*/
    user.put(location, json.optString(location));
    user.put(description, json.optString(description));
    user.put(url, json.optString(url));
    user.put(profile_image_url, json.optString(profile_image_url));
    user.put(cover_image, json.optString(cover_image));
    user.put(cover_image_phone, json.optString(cover_image_phone));
    user.put(profile_url, json.optString(profile_url));
    user.put(domain, json.optString(domain));
    user.put(weihao, json.optString(weihao));
    user.put(gender, json.optString(gender));
    user.put(followers_count, json.optInt(followers_count));
    user.put(friends_count, json.optInt(friends_count));
    user.put(statuses_count, json.optInt(statuses_count));
    user.put(favourites_count, json.optInt(favourites_count));
    user.put(created_at, json.optString(created_at));
    user.put(following, json.optBoolean(following));
    user.put(allow_all_act_msg, json.optBoolean(allow_all_act_msg));
    user.put(geo_enabled, json.optBoolean(geo_enabled));
    user.put(verified, json.optBoolean(verified));
    user.put(verified_type, json.optInt(verified_type));
    user.put(remark, json.optString(remark));
    //      user.put(ptype, json.optInt(ptype));
    user.put(allow_all_comment, json.optBoolean(allow_all_comment));
    user.put(avatar_large, json.optString(avatar_large));
    user.put(avatar_hd, json.optString(avatar_hd));
    user.put(verified_reason, json.optString(verified_reason));
    user.put(follow_me, json.optBoolean(follow_me));
    user.put(online_status, json.optInt(online_status));
    user.put(bi_followers_count, json.optInt(bi_followers_count));
    user.put(lang, json.optString(lang));
    //      user.put(star, json.optString(star));
    //      user.put(mbtype, json.optInt(mbtype));
    //      user.put(mbrank, json.optInt(mbrank));
    //      user.put(block_word, json.optInt(block_word));
    // ?id
    if (json.has(SINGLE)) {
        user.put(status_id, json.optJSONObject(Status.SINGLE).optLong(Constants.ID));
    }
    return user;
}

From source file:com.mindmeapp.extensions.ExtensionData.java

/**
 * Deserializes the given JSON representation of extension data, populating this
 * object.//from www.  ja  va 2  s .  c o  m
 */
public void deserialize(JSONObject data) throws JSONException {
    this.mVisible = data.optBoolean(KEY_VISIBLE);
    this.mIcon = data.optInt(KEY_ICON);
    String iconUriString = data.optString(KEY_ICON_URI);
    this.mIconUri = TextUtils.isEmpty(iconUriString) ? null : Uri.parse(iconUriString);
    this.mStatusToDisplay = data.optString(KEY_STATUS_TO_DISPLAY);
    this.mStatusToSpeak = data.optString(KEY_STATUS_TO_SPEAK);
    this.mContentDescription = data.optString(KEY_CONTENT_DESCRIPTION);
    this.mBackground = data.optInt(KEY_BACKGROUND);
    String backgroundUriString = data.optString(KEY_BACKGROUND_URI);
    this.mBackgroundUri = TextUtils.isEmpty(backgroundUriString) ? null : Uri.parse(backgroundUriString);

    //Build back the Locale object
    String language = data.optString(KEY_LOCALE_LANGUAGE);
    String country = data.optString(KEY_LOCALE_COUNTRY);
    if (TextUtils.isEmpty(country)) {
        this.mLanguageToSpeak = new Locale(language);
    } else {
        this.mLanguageToSpeak = new Locale(language, country);
    }

}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.ProfilePictureObj.java

public boolean handleObjFromNetwork(Context context, Contact from, JSONObject obj) {
    byte[] data = FastBase64.decode(obj.optString(DATA));
    boolean reply = obj.optBoolean(REPLY);

    String id = Long.toString(from.id);
    ContentValues values = new ContentValues();
    values.put(Contact.PICTURE, data);//from w w  w. jav a  2 s . c o m
    context.getContentResolver().update(Uri.parse(DungBeetleContentProvider.CONTENT_URI + "/contacts"), values,
            "_id=?", new String[] { id });
    Helpers.invalidateContacts();

    if (reply) {
        LinkedList<Contact> contacts = new LinkedList<Contact>();
        contacts.add(from);
        Helpers.resendProfile(context, contacts, false);
    }
    return false;
}

From source file:at.alladin.rmbt.android.util.CheckSettingsTask.java

/**
* 
*///  ww w . jav  a  2 s  . c  o  m
@Override
protected void onPostExecute(final JSONArray resultList) {
    try {
        if (serverConn.hasError())
            hasError = true;
        else if (resultList != null && resultList.length() > 0) {

            JSONObject resultListItem;

            try {
                resultListItem = resultList.getJSONObject(0);

                /* UUID */

                final String uuid = resultListItem.optString("uuid", "");
                if (uuid != null && uuid.length() != 0)
                    ConfigHelper.setUUID(activity.getApplicationContext(), uuid);

                /* urls */

                final ConcurrentMap<String, String> volatileSettings = ConfigHelper.getVolatileSettings();

                final JSONObject urls = resultListItem.optJSONObject("urls");
                if (urls != null) {
                    final Iterator<String> keys = urls.keys();

                    while (keys.hasNext()) {
                        final String key = keys.next();
                        final String value = urls.optString(key, null);
                        if (value != null) {
                            volatileSettings.put("url_" + key, value);
                            if ("statistics".equals(key)) {
                                ConfigHelper.setCachedStatisticsUrl(value, activity);
                            } else if ("control_ipv4_only".equals(key)) {
                                ConfigHelper.setCachedControlServerNameIpv4(value, activity);
                            } else if ("control_ipv6_only".equals(key)) {
                                ConfigHelper.setCachedControlServerNameIpv6(value, activity);
                            } else if ("url_ipv4_check".equals(key)) {
                                ConfigHelper.setCachedIpv4CheckUrl(value, activity);
                            } else if ("url_ipv6_check".equals(key)) {
                                ConfigHelper.setCachedIpv6CheckUrl(value, activity);
                            }
                        }
                    }
                }

                /* qos names */
                final JSONArray qosNames = resultListItem.optJSONArray("qostesttype_desc");
                if (qosNames != null) {
                    final Map<String, String> qosNamesMap = new HashMap<String, String>();
                    for (int i = 0; i < qosNames.length(); i++) {
                        JSONObject json = qosNames.getJSONObject(i);
                        qosNamesMap.put(json.optString("test_type"), json.optString("name"));
                    }
                    ConfigHelper.setCachedQoSNames(qosNamesMap, activity);
                }

                /* map server */

                final JSONObject mapServer = resultListItem.optJSONObject("map_server");
                if (mapServer != null) {
                    final String host = mapServer.optString("host");
                    final int port = mapServer.optInt("port");
                    final boolean ssl = mapServer.optBoolean("ssl");
                    if (host != null && port > 0)
                        ConfigHelper.setMapServer(host, port, ssl);
                }

                /* control server version */
                final JSONObject versions = resultListItem.optJSONObject("versions");
                if (versions != null) {
                    if (versions.has("control_server_version")) {
                        ConfigHelper.setControlServerVersion(activity,
                                versions.optString("control_server_version"));
                    }
                }

                // ///////////////////////////////////////////////////////
                // HISTORY / FILTER

                final JSONObject historyObject = resultListItem.getJSONObject("history");

                final JSONArray deviceArray = historyObject.getJSONArray("devices");
                final JSONArray networkArray = historyObject.getJSONArray("networks");

                final String historyDevices[] = new String[deviceArray.length()];

                for (int i = 0; i < deviceArray.length(); i++)
                    historyDevices[i] = deviceArray.getString(i);

                final String historyNetworks[] = new String[networkArray.length()];

                for (int i = 0; i < networkArray.length(); i++)
                    historyNetworks[i] = networkArray.getString(i);

                // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////

                activity.setSettings(historyDevices, historyNetworks);

                activity.setHistoryDirty(true);

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

        } else
            Log.i(DEBUG_TAG, "LEERE LISTE");
    } finally {
        if (endTaskListener != null)
            endTaskListener.taskEnded(resultList);
    }
}

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

private void injectProfile(JSONObject json) {
    // ?//  w  w  w  .jav  a 2s  . co  m
    mUid = json.optLong(Constants.ID);
    mAvatarUrl = json.optString(User.avatar_large);
    mAvatarHdUrl = json.optString(User.avatar_hd);
    mVerified = json.optBoolean(User.verified);
    mRemark = json.optString(User.remark);
    mDescription = json.optString(User.description);
    mLocation = json.optString(User.location);
    mProfileUrl = json.optString(User.profile_url);
    mCoverUrl = json.optString(User.cover_image);
    mVerifiedReason = json.optString(User.verified_reason);
    // +
    mFollowing = json.optBoolean(User.following);
    // menu
    buildMenu();
    // load??
    if (!TextUtils.isEmpty(mCoverUrl)) {
        Picasso.with(getActivity()).load(mCoverUrl).placeholder(R.drawable.default_fantasy)
                .error(R.drawable.default_fantasy).into(profileTarget);
    } else {
        mPlaceHolder.setBackground(getResources().getDrawable(R.drawable.default_fantasy));
    }
    // ?
    mTweetsCount.setOnClickListener(tweetsOnclickListener);
    CatnutUtils.setText(mTweetsCount, android.R.id.text1, json.optString(User.statuses_count));
    CatnutUtils.setText(mTweetsCount, android.R.id.text2, getString(R.string.tweets));
    // 
    mFollowersCount.setOnClickListener(followersOnclickListener);
    CatnutUtils.setText(mFollowersCount, android.R.id.text1, json.optString(User.followers_count));
    CatnutUtils.setText(mFollowersCount, android.R.id.text2, getString(R.string.followers));
    // 
    mFollowingsCount.setOnClickListener(followingsOnClickListener);
    CatnutUtils.setText(mFollowingsCount, android.R.id.text1, json.optString(User.friends_count));

    CatnutUtils.setText(mFollowingsCount, android.R.id.text2, getString(R.string.followings));
    // pager adapter, not fragment pager any more
    mViewPager.setAdapter(coverPager);
    mIndicator.setViewPager(mViewPager);
}

From source file:com.facebook.internal.LikeActionController.java

private static LikeActionController deserializeFromJson(String controllerJsonString) {
    LikeActionController controller;/*from   w w w  .  j  a va  2 s  . c  o m*/

    try {
        JSONObject controllerJson = new JSONObject(controllerJsonString);
        int version = controllerJson.optInt(JSON_INT_VERSION_KEY, -1);
        if (version != LIKE_ACTION_CONTROLLER_VERSION) {
            // Don't attempt to deserialize a controller that might be serialized differently than expected.
            return null;
        }

        controller = new LikeActionController(Session.getActiveSession(),
                controllerJson.getString(JSON_STRING_OBJECT_ID_KEY));

        // Make sure to default to null and not empty string, to keep the logic elsewhere functioning properly.
        controller.likeCountStringWithLike = controllerJson.optString(JSON_STRING_LIKE_COUNT_WITH_LIKE_KEY,
                null);
        controller.likeCountStringWithoutLike = controllerJson
                .optString(JSON_STRING_LIKE_COUNT_WITHOUT_LIKE_KEY, null);
        controller.socialSentenceWithLike = controllerJson.optString(JSON_STRING_SOCIAL_SENTENCE_WITH_LIKE_KEY,
                null);
        controller.socialSentenceWithoutLike = controllerJson
                .optString(JSON_STRING_SOCIAL_SENTENCE_WITHOUT_LIKE_KEY, null);
        controller.isObjectLiked = controllerJson.optBoolean(JSON_BOOL_IS_OBJECT_LIKED_KEY);
        controller.unlikeToken = controllerJson.optString(JSON_STRING_UNLIKE_TOKEN_KEY, null);
        String pendingCallIdString = controllerJson.optString(JSON_STRING_PENDING_CALL_ID_KEY, null);
        if (!Utility.isNullOrEmpty(pendingCallIdString)) {
            controller.pendingCallId = UUID.fromString(pendingCallIdString);
        }

        JSONObject analyticsJSON = controllerJson.optJSONObject(JSON_BUNDLE_PENDING_CALL_ANALYTICS_BUNDLE);
        if (analyticsJSON != null) {
            controller.pendingCallAnalyticsBundle = BundleJSONConverter.convertToBundle(analyticsJSON);
        }
    } catch (JSONException e) {
        Log.e(TAG, "Unable to deserialize controller from JSON", e);
        controller = null;
    }

    return controller;
}

From source file:com.marlonjones.voidlauncher.InstallShortcutReceiver.java

private static PendingInstallShortcutInfo decode(String encoded, Context context) {
    try {/*from   w  w  w.  jav a2 s .  c  o  m*/
        JSONObject object = (JSONObject) new JSONTokener(encoded).nextValue();
        Intent launcherIntent = Intent.parseUri(object.getString(LAUNCH_INTENT_KEY), 0);

        if (object.optBoolean(APP_SHORTCUT_TYPE_KEY)) {
            // The is an internal launcher target shortcut.
            UserHandleCompat user = UserManagerCompat.getInstance(context)
                    .getUserForSerialNumber(object.getLong(USER_HANDLE_KEY));
            if (user == null) {
                return null;
            }

            LauncherActivityInfoCompat info = LauncherAppsCompat.getInstance(context)
                    .resolveActivity(launcherIntent, user);
            return info == null ? null : new PendingInstallShortcutInfo(info, context);
        }

        Intent data = new Intent();
        data.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launcherIntent);
        data.putExtra(Intent.EXTRA_SHORTCUT_NAME, object.getString(NAME_KEY));

        String iconBase64 = object.optString(ICON_KEY);
        String iconResourceName = object.optString(ICON_RESOURCE_NAME_KEY);
        String iconResourcePackageName = object.optString(ICON_RESOURCE_PACKAGE_NAME_KEY);
        if (iconBase64 != null && !iconBase64.isEmpty()) {
            byte[] iconArray = Base64.decode(iconBase64, Base64.DEFAULT);
            Bitmap b = BitmapFactory.decodeByteArray(iconArray, 0, iconArray.length);
            data.putExtra(Intent.EXTRA_SHORTCUT_ICON, b);
        } else if (iconResourceName != null && !iconResourceName.isEmpty()) {
            Intent.ShortcutIconResource iconResource = new Intent.ShortcutIconResource();
            iconResource.resourceName = iconResourceName;
            iconResource.packageName = iconResourcePackageName;
            data.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
        }

        return new PendingInstallShortcutInfo(data, context);
    } catch (JSONException | URISyntaxException e) {
        Log.d(TAG, "Exception reading shortcut to add: " + e);
    }
    return null;
}

From source file:fr.cobaltians.cobalt.fragments.CobaltFragment.java

/**
 * This method is called when the JavaScript sends a message to the native side.
 * This method should be overridden in subclasses.
 * @param message : the JSON-message sent by JavaScript.
 * @return true if the message was handled by the native, false otherwise
 * @details some basic operations are already implemented : navigation, logs, toasts, native alerts, web alerts
 * @details this method may be called from a secondary thread.
 *//*from w w w.  j a v  a  2  s.  c o m*/
// This method must be public !!!
@JavascriptInterface
public boolean onCobaltMessage(String message) {
    try {
        final JSONObject jsonObj = new JSONObject(message);

        // TYPE
        if (jsonObj.has(Cobalt.kJSType)) {
            String type = jsonObj.getString(Cobalt.kJSType);

            //CALLBACK
            if (type.equals(Cobalt.JSTypeCallBack)) {
                String callbackID = jsonObj.getString(Cobalt.kJSCallback);
                JSONObject data = jsonObj.optJSONObject(Cobalt.kJSData);

                return handleCallback(callbackID, data);
            }

            // COBALT IS READY
            else if (type.equals(Cobalt.JSTypeCobaltIsReady)) {
                String versionWeb = jsonObj.optString(Cobalt.kJSVersion, null);
                String versionNative = getResources().getString(R.string.version_name);
                if (versionWeb != null && !versionWeb.equals(versionNative))
                    Log.e(TAG, "Warning : Cobalt version mismatch : Android Cobalt version is " + versionNative
                            + " but Web Cobalt version is " + versionWeb + ". You should fix this. ");
                onCobaltIsReady();
                return true;
            }

            // EVENT
            else if (type.equals(Cobalt.JSTypeEvent)) {
                String event = jsonObj.getString(Cobalt.kJSEvent);
                JSONObject data = jsonObj.optJSONObject(Cobalt.kJSData);
                String callback = jsonObj.optString(Cobalt.kJSCallback, null);

                return handleEvent(event, data, callback);
            }

            // INTENT
            else if (type.equals(Cobalt.JSTypeIntent)) {
                String action = jsonObj.getString(Cobalt.kJSAction);

                // OPEN EXTERNAL URL
                if (action.equals(Cobalt.JSActionIntentOpenExternalUrl)) {
                    JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);
                    String url = data.getString(Cobalt.kJSUrl);
                    openExternalUrl(url);

                    return true;
                }

                // UNHANDLED INTENT
                else {
                    onUnhandledMessage(jsonObj);
                }
            }

            // LOG
            else if (type.equals(Cobalt.JSTypeLog)) {
                String text = jsonObj.getString(Cobalt.kJSValue);
                Log.d(Cobalt.TAG, "JS LOG: " + text);
                return true;
            }

            // NAVIGATION
            else if (type.equals(Cobalt.JSTypeNavigation)) {
                String action = jsonObj.getString(Cobalt.kJSAction);

                // PUSH
                if (action.equals(Cobalt.JSActionNavigationPush)) {
                    JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);
                    String page = data.getString(Cobalt.kJSPage);
                    String controller = data.optString(Cobalt.kJSController, null);
                    push(controller, page);
                    return true;
                }

                // POP
                else if (action.equals(Cobalt.JSActionNavigationPop)) {
                    JSONObject data = jsonObj.optJSONObject(Cobalt.kJSData);
                    if (data != null) {
                        String page = data.getString(Cobalt.kJSPage);
                        String controller = data.optString(Cobalt.kJSController, null);
                        pop(controller, page);
                    } else
                        pop();
                    return true;
                }

                // MODAL
                else if (action.equals(Cobalt.JSActionNavigationModal)) {
                    JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);
                    String page = data.getString(Cobalt.kJSPage);
                    String controller = data.optString(Cobalt.kJSController, null);
                    String callbackId = jsonObj.optString(Cobalt.kJSCallback, null);
                    presentModal(controller, page, callbackId);
                    return true;
                }

                // DISMISS
                else if (action.equals(Cobalt.JSActionNavigationDismiss)) {
                    // TODO: not present in iOS
                    JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);
                    String controller = data.getString(Cobalt.kJSController);
                    String page = data.getString(Cobalt.kJSPage);
                    dismissModal(controller, page);
                    return true;
                }

                //REPLACE
                else if (action.equals(Cobalt.JSActionNavigationReplace)) {
                    JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);
                    String controller = data.getString(Cobalt.kJSController);
                    String page = data.getString(Cobalt.kJSPage);
                    boolean animated = data.optBoolean(Cobalt.kJSAnimated);
                    replace(controller, page, animated);
                    return true;
                }

                // UNHANDLED NAVIGATION
                else {
                    onUnhandledMessage(jsonObj);
                }
            }

            // PLUGIN
            else if (type.equals(Cobalt.JSTypePlugin)) {
                mPluginManager.onMessage(mContext, this, jsonObj);
            }

            // UI
            else if (type.equals(Cobalt.JSTypeUI)) {
                String control = jsonObj.getString(Cobalt.kJSUIControl);
                JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);
                String callback = jsonObj.optString(Cobalt.kJSCallback, null);

                return handleUi(control, data, callback);
            }

            // WEB LAYER
            else if (type.equals(Cobalt.JSTypeWebLayer)) {
                String action = jsonObj.getString(Cobalt.kJSAction);

                // SHOW
                if (action.equals(Cobalt.JSActionWebLayerShow)) {
                    final JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);

                    mHandler.post(new Runnable() {

                        @Override
                        public void run() {
                            showWebLayer(data);
                        }
                    });

                    return true;
                }

                // UNHANDLED WEB LAYER
                else {
                    onUnhandledMessage(jsonObj);
                }
            }

            // UNHANDLED TYPE
            else {
                onUnhandledMessage(jsonObj);
            }
        }

        // UNHANDLED MESSAGE
        else {
            onUnhandledMessage(jsonObj);
        }
    } catch (JSONException exception) {
        if (Cobalt.DEBUG)
            Log.e(Cobalt.TAG, TAG + " - onCobaltMessage: JSONException");
        exception.printStackTrace();
    } catch (NullPointerException exception) {
        if (Cobalt.DEBUG)
            Log.e(Cobalt.TAG, TAG + " - onCobaltMessage: NullPointerException");
        exception.printStackTrace();
    }

    return false;
}