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:com.hhunj.hhudata.ForegroundService.java

private SearchBookContentsResult parseResult(JSONObject json) {
    try {/* w w w .j  a v a  2 s  .  c  o  m*/
        String pageId = json.getString("page_id");
        String pageNumber = json.getString("page_number");
        if (pageNumber.length() > 0) {
            // pageNumber = getString(R.string.msg_sbc_page) + ' ' +
            // pageNumber;
        } else {
            // This can happen for text on the jacket, and possibly other
            // reasons.
            // pageNumber = getString(R.string.msg_sbc_unknown_page);
            pageNumber = null;
        }

        // Remove all HTML tags and encoded characters. Ideally the server
        // would do this.
        String snippet = json.optString("snippet_text");
        boolean valid = true;
        if (snippet.length() > 0) {
            /*
             * snippet = TAG_PATTERN.matcher(snippet).replaceAll("");
             * snippet = LT_ENTITY_PATTERN.matcher(snippet).replaceAll("<");
             * snippet = GT_ENTITY_PATTERN.matcher(snippet).replaceAll(">");
             * snippet =
             * QUOTE_ENTITY_PATTERN.matcher(snippet).replaceAll("'");
             * snippet =
             * QUOT_ENTITY_PATTERN.matcher(snippet).replaceAll("\"");
             */
        } else {
            snippet = '(' + getString(R.string.msg_sbc_snippet_unavailable) + ')';
            valid = false;
        }
        // new Date(+/\d+/.exec(value)[1]);

        Date date = JsonToDateTime(json.getString("rectime"));
        if (date == null)
            return null;

        return new SearchBookContentsResult(pageId, pageNumber, snippet, valid, date);

    } catch (JSONException e) {

        Date date = new Date();
        // Never seen in the wild, just being complete.
        return new SearchBookContentsResult(getString(R.string.msg_sbc_no_page_returned), "", "", false, date);
    }
}

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

private static PendingInstallShortcutInfo decode(String encoded, Context context) {
    try {/*from   w w w  . ja  va 2 s .co  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

/******************************************************************************************************************
 * ALERT DIALOG/* ww w  . j a  v  a2 s.c  om*/
 *****************************************************************************************************************/

private void showAlertDialog(JSONObject data, final String callback) {
    try {
        String title = data.optString(Cobalt.kJSAlertTitle);
        String message = data.optString(Cobalt.kJSMessage);
        boolean cancelable = data.optBoolean(Cobalt.kJSAlertCancelable, false);
        JSONArray buttons = data.has(Cobalt.kJSAlertButtons) ? data.getJSONArray(Cobalt.kJSAlertButtons)
                : new JSONArray();

        AlertDialog alertDialog = new AlertDialog.Builder(mContext).setTitle(title).setMessage(message)
                .create();
        alertDialog.setCancelable(cancelable);

        if (buttons.length() == 0) {
            alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "OK", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (callback != null) {
                        try {
                            JSONObject data = new JSONObject();
                            data.put(Cobalt.kJSAlertButtonIndex, 0);
                            sendCallback(callback, data);
                        } catch (JSONException exception) {
                            if (Cobalt.DEBUG)
                                Log.e(Cobalt.TAG, TAG + ".AlertDialog - onClick: JSONException");
                            exception.printStackTrace();
                        }
                    }
                }
            });
        } else {
            int buttonsLength = Math.min(buttons.length(), 3);
            for (int i = 0; i < buttonsLength; i++) {
                int buttonId;

                switch (i) {
                case 0:
                default:
                    buttonId = DialogInterface.BUTTON_NEGATIVE;
                    break;
                case 1:
                    buttonId = DialogInterface.BUTTON_NEUTRAL;
                    break;
                case 2:
                    buttonId = DialogInterface.BUTTON_POSITIVE;
                    break;
                }

                alertDialog.setButton(buttonId, buttons.getString(i), new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (callback != null) {
                            int buttonIndex;
                            switch (which) {
                            case DialogInterface.BUTTON_NEGATIVE:
                            default:
                                buttonIndex = 0;
                                break;
                            case DialogInterface.BUTTON_NEUTRAL:
                                buttonIndex = 1;
                                break;
                            case DialogInterface.BUTTON_POSITIVE:
                                buttonIndex = 2;
                                break;
                            }

                            try {
                                JSONObject data = new JSONObject();
                                data.put(Cobalt.kJSAlertButtonIndex, buttonIndex);
                                sendCallback(callback, data);
                            } catch (JSONException exception) {
                                if (Cobalt.DEBUG)
                                    Log.e(Cobalt.TAG, TAG + ".AlertDialog - onClick: JSONException");
                                exception.printStackTrace();
                            }
                        }
                    }
                });
            }
        }

        alertDialog.show();
    } catch (JSONException exception) {
        if (Cobalt.DEBUG)
            Log.e(Cobalt.TAG, TAG + " - showAlertDialog: JSONException");
        exception.printStackTrace();
    }
}

From source file:se.frostyelk.cordova.amazon.ads.AmazonAds.java

private PluginResult executeCreateInterstitialAd(JSONObject options, final CallbackContext callbackContext) {
    if (options.has(OPTION_INTERSTITIAL_AD_ID)) {
        interstitialAdId = options.optString(OPTION_INTERSTITIAL_AD_ID);
    } else {//from w  w w  .  j a v a2  s .  c om
        return new PluginResult(Status.ERROR, "Option " + OPTION_INTERSTITIAL_AD_ID + " is missing");
    }

    if (options.has(OPTION_IS_TESTING)) {
        try {
            isTesting = options.getBoolean(OPTION_IS_TESTING);
        } catch (JSONException e) {
            return new PluginResult(Status.ERROR, "Value of option " + OPTION_IS_TESTING + " is wrong");
        }
    }

    if (options.has(OPTION_DEBUG)) {
        try {
            AdRegistration.enableLogging(options.getBoolean(OPTION_DEBUG));
        } catch (JSONException e) {
            return new PluginResult(Status.ERROR, "Value of option " + OPTION_DEBUG + " is wrong");
        }
    } else {
        AdRegistration.enableLogging(false);
    }

    if (callbackContext == null) {
        return new PluginResult(Status.ERROR, "Callback function is missing");
    }

    cordova.getThreadPool().execute(new Runnable() {
        @Override
        public void run() {

            if (interstitialAd == null) {
                interstitialAd = new InterstitialAd(cordova.getActivity());
                interstitialAd.setListener(new AmazonInterstitialAdListener());
            }

            AdRegistration.enableTesting(isTesting);

            try {
                AdRegistration.setAppKey(interstitialAdId);
            } catch (final IllegalArgumentException e) {
                callbackContext.error("Value of " + OPTION_INTERSTITIAL_AD_ID + " is wrong");
                return;
            }

            if (interstitialAd.loadAd()) {
                if (callbackContext != null) {
                    callbackContext.success();
                }
            } else {
                if (callbackContext != null) {
                    callbackContext.error("Failed to create Ad");
                }
            }
        }
    });

    return null;
}

From source file:com.cloudstudio.BarcodeScanner.java

/**
 * Executes the request./*from   w ww. ja va2  s . c  o  m*/
 *
 * This method is called from the WebView thread. To do a non-trivial amount of work, use:
 *     cordova.getThreadPool().execute(runnable);
 *
 * To run on the UI thread, use:
 *     cordova.getActivity().runOnUiThread(runnable);
 *
 * @param action          The action to execute.
 * @param args            The exec() arguments.
 * @param callbackContext The callback context used when calling back into JavaScript.
 * @return                Whether the action was valid.
 *
 * @sa https://github.com/apache/cordova-android/blob/master/framework/src/org/apache/cordova/CordovaPlugin.java
 */
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    this.callbackContext = callbackContext;

    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) {
                callbackContext.error("User did not specify data to encode");
                return true;
            }

            encode(type, data);
        } else {
            callbackContext.error("User did not specify data to encode");
            return true;
        }
    } else if (action.equals(SCAN)) {
        scan();
    } else {
        return false;
    }
    return true;
}

From source file:com.weiboa.data.WeiboConnect.java

public static String getScreenName(JSONObject credentials) {
    return credentials.optString("screen_name");
}

From source file:samples.piggate.com.piggateInfoDemo.Service_Notify.java

public void updateNotificationMsg() {

    if (checkInternetConnection() == true) { //If the internet connection is working

        //Only request the notification message when is missing or set by default
        if (notificationMsg.equals(defaultMsg) || notificationMsg.equals("")) {

            _piggate.RequestGetNotification().setListenerRequest(new Piggate.PiggateCallBack() {
                @Override//from   w  w  w .j  av  a2s  .c o m
                public void onComplete(int statusCode, Header[] headers, String msg, JSONObject data) {
                    //Get the notification message
                    Service_Notify.notificationtitle = data.optString("title");
                    Service_Notify.notificationMsg = data.optString("msg");
                }

                @Override
                public void onError(int statusCode, Header[] headers, String msg, JSONObject data) {
                    //Default message if there's an error
                    Service_Notify.notificationtitle = defaultTitle;
                    Service_Notify.notificationMsg = defaultMsg;
                }

                @Override
                public void onComplete(int statusCode, Header[] headers, String msg, JSONArray data) {
                    //Unused
                }

                @Override
                public void onError(int statusCode, Header[] headers, String msg, JSONArray data) {
                    //Unused
                }
            }).exec();
        }
    } else {
        Service_Notify.notificationMsg = defaultMsg; //Default message if there's a network error
    }
}

From source file:org.b3log.latke.user.local.LocalUserService.java

@Override
public GeneralUser getCurrentUser(final HttpServletRequest request) {
    final JSONObject currentUser = Sessions.currentUser(request);

    if (null == currentUser) {
        return null;
    }/*from w w w  . ja va 2 s  . c  om*/

    final GeneralUser ret = new GeneralUser();

    ret.setEmail(currentUser.optString(User.USER_EMAIL));
    ret.setId(currentUser.optString(Keys.OBJECT_ID));
    ret.setNickname(currentUser.optString(User.USER_NAME));

    return ret;
}

From source file:org.b3log.latke.user.local.LocalUserService.java

@Override
public boolean isUserAdmin(final HttpServletRequest request) {
    final JSONObject currentUser = Sessions.currentUser(request);

    if (null == currentUser) {
        return false;
    }//from  ww  w . j  av  a 2  s. co  m

    return Role.ADMIN_ROLE.equals(currentUser.optString(User.USER_ROLE));
}

From source file:cn.ttyhuo.activity.InfoOwnerActivity.java

protected void setupViewOfHasLogin(JSONObject jObject) {
    try {/*from w w  w  . j a v a  2  s  .  c  o  m*/

        ArrayList<String> pics = new ArrayList<String>();
        JSONArray jsonArray = jObject.optJSONArray("imageList");
        if (jsonArray != null) {
            for (int s = 0; s < jsonArray.length(); s++)
                pics.add(jsonArray.getString(s));
        }
        while (pics.size() < 3)
            pics.add("plus");
        mPicData = pics;
        mPicAdapter.updateData(pics);

        if (jObject.getBoolean("isTruckVerified")) {
            tv_edit_tips.setText("?????");
        } else if (jsonArray != null && jsonArray.length() > 2 && jObject.has("truckInfo")) {
            tv_edit_tips.setText(
                    "?????????");
        } else {
            tv_edit_tips.setText("??????");
        }

        if (jObject.has("truckInfo")) {
            JSONObject userJsonObj = jObject.getJSONObject("truckInfo");
            if (!userJsonObj.optString("licensePlate").isEmpty()
                    && userJsonObj.optString("licensePlate") != "null")
                mEditChepai.setText(userJsonObj.getString("licensePlate"));
            Integer truckType = userJsonObj.getInt("truckType");
            if (truckType != null && truckType > 0)
                mEditChexing.setText(ConstHolder.TruckTypeItems[truckType - 1]);
            else
                mEditChexing.setText("");
            if (!userJsonObj.optString("loadLimit").isEmpty() && userJsonObj.optString("loadLimit") != "null")
                mEditZaizhong.setText(userJsonObj.getString("loadLimit"));
            if (!userJsonObj.optString("truckLength").isEmpty()
                    && userJsonObj.optString("truckLength") != "null")
                mEditChechang.setText(userJsonObj.getString("truckLength"));
            if (!userJsonObj.optString("modelNumber").isEmpty()
                    && userJsonObj.optString("modelNumber") != "null")
                mEditXinghao.setText(userJsonObj.getString("modelNumber"));

            if (!userJsonObj.optString("seatingCapacity").isEmpty()
                    && userJsonObj.optString("seatingCapacity") != "null")
                mEditZuowei.setText(userJsonObj.getString("seatingCapacity"));
            if (!userJsonObj.optString("releaseYear").isEmpty()
                    && userJsonObj.optString("releaseYear") != "null")
                mEditDate.setText(userJsonObj.getString("releaseYear") + "");
            if (!userJsonObj.optString("truckWidth").isEmpty() && userJsonObj.optString("truckWidth") != "null")
                mEditKuan.setText(userJsonObj.getString("truckWidth"));
            if (!userJsonObj.optString("truckHeight").isEmpty()
                    && userJsonObj.optString("truckHeight") != "null")
                mEditGao.setText(userJsonObj.getString("truckHeight"));
        }

        if (!jObject.getBoolean("isTruckVerified")) {
            mEditChexing.setOnClickListener(this);
            mEditDate.setOnClickListener(this);
            mEditChepai.setFocusable(true);
            mEditChepai.setEnabled(true);
            mEditZaizhong.setFocusable(true);
            mEditZaizhong.setEnabled(true);
            mEditChechang.setFocusable(true);
            mEditChechang.setEnabled(true);
            mEditZuowei.setFocusable(true);
            mEditZuowei.setEnabled(true);
            mEditKuan.setFocusable(true);
            mEditKuan.setEnabled(true);
            mEditGao.setFocusable(true);
            mEditGao.setEnabled(true);
            mEditXinghao.setFocusable(true);
            mEditXinghao.setEnabled(true);
            canUpdate = true;
        } else {
            mPicGrid.setOnItemLongClickListener(null);

            mEditChepai.setFocusable(false);
            mEditChepai.setEnabled(false);
            mEditZaizhong.setFocusable(false);
            mEditZaizhong.setEnabled(false);
            mEditChechang.setFocusable(false);
            mEditChechang.setEnabled(false);
            mEditZuowei.setFocusable(false);
            mEditZuowei.setEnabled(false);
            mEditKuan.setFocusable(false);
            mEditKuan.setEnabled(false);
            mEditGao.setFocusable(false);
            mEditGao.setEnabled(false);
            mEditXinghao.setFocusable(false);
            mEditXinghao.setEnabled(false);
            canUpdate = false;
        }

        saveParams(true);

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