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.claude.sharecam.util.CountryMaster.java

private CountryMaster(Context context) {
    mContext = context;/*w  w w  . j  a  v  a  2  s .  co m*/
    Resources res = mContext.getResources();

    // builds country data from json
    InputStream is = res.openRawResource(R.raw.countries);
    Writer writer = new StringWriter();
    char[] buffer = new char[1024];
    try {
        Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        int n;
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    String jsonString = writer.toString();
    JSONArray json = new JSONArray();
    try {
        json = new JSONArray(jsonString);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    mCountryList = new String[json.length()];
    for (int i = 0; i < json.length(); i++) {
        JSONObject node = json.optJSONObject(i);
        if (node != null) {
            Country country = new Country();
            country.mCountryIso = node.optString("iso");
            country.mDialPrefix = node.optString("tel");
            country.mCountryName = getCountryName(node.optString("iso"));
            mCountries.add(country);
            mCountryList[i] = country.mCountryIso;
        }
    }
}

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 va2s . co m*/

    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.phonegap.ContactAccessorSdk3_4.java

@Override
/** //from  ww  w. j  a  va 2 s . c  o  m
 * This method takes the fields required and search options in order to produce an 
 * array of contacts that matches the criteria provided.
 * @param fields an array of items to be used as search criteria
 * @param options that can be applied to contact searching
 * @return an array of contacts 
 */
public JSONArray search(JSONArray fields, JSONObject options) {
    String searchTerm = "";
    int limit = Integer.MAX_VALUE;
    boolean multiple = true;

    if (options != null) {
        searchTerm = options.optString("filter");
        if (searchTerm.length() == 0) {
            searchTerm = "%";
        } else {
            searchTerm = "%" + searchTerm + "%";
        }
        try {
            multiple = options.getBoolean("multiple");
            if (!multiple) {
                limit = 1;
            }
        } catch (JSONException e) {
            // Multiple was not specified so we assume the default is true.
        }
    } else {
        searchTerm = "%";
    }

    ContentResolver cr = mApp.getContentResolver();

    Set<String> contactIds = buildSetOfContactIds(fields, searchTerm);
    HashMap<String, Boolean> populate = buildPopulationSet(fields);

    Iterator<String> it = contactIds.iterator();

    JSONArray contacts = new JSONArray();
    JSONObject contact;
    String contactId;
    int pos = 0;
    while (it.hasNext() && (pos < limit)) {
        contact = new JSONObject();
        try {
            contactId = it.next();
            contact.put("id", contactId);

            // Do query for name and note
            Cursor cur = cr.query(People.CONTENT_URI, new String[] { People.DISPLAY_NAME, People.NOTES },
                    PEOPLE_ID_EQUALS, new String[] { contactId }, null);
            cur.moveToFirst();

            if (isRequired("displayName", populate)) {
                contact.put("displayName", cur.getString(cur.getColumnIndex(People.DISPLAY_NAME)));
            }
            if (isRequired("phoneNumbers", populate)) {
                contact.put("phoneNumbers", phoneQuery(cr, contactId));
            }
            if (isRequired("emails", populate)) {
                contact.put("emails", emailQuery(cr, contactId));
            }
            if (isRequired("addresses", populate)) {
                contact.put("addresses", addressQuery(cr, contactId));
            }
            if (isRequired("organizations", populate)) {
                contact.put("organizations", organizationQuery(cr, contactId));
            }
            if (isRequired("ims", populate)) {
                contact.put("ims", imQuery(cr, contactId));
            }
            if (isRequired("note", populate)) {
                contact.put("note", cur.getString(cur.getColumnIndex(People.NOTES)));
            }
            // nickname
            // urls
            // relationship
            // birthdays
            // anniversary

            pos++;
            cur.close();
        } catch (JSONException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        }
        contacts.put(contact);
    }
    return contacts;
}

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

public static SrnSecondaryTemplate createSecondaryTemplate(Context mContext, RichNotificationOptions options)
        throws JSONException {
    SrnSecondaryTemplate secondaryTemplate = null;
    //In case of Seconday Type None
    if (options.secondaryType.equalsIgnoreCase(RichNotificationHelper.SECONDARY_TYPE_NONE)) {
        return null;
    } //In case of Seconday Type Standard
    else if (options.secondaryType.equalsIgnoreCase(RichNotificationHelper.SECONDARY_TYPE_STD)) {
        SrnStandardSecondaryTemplate stdSecondary = new SrnStandardSecondaryTemplate();
        stdSecondary.setSubHeader(options.secondarySubHeader);

        if (options.secondaryContent != null) {
            JSONObject content = options.secondaryContent.optJSONObject(0);
            if (content != null) {
                stdSecondary.setTitle(content.optString("title"));
                stdSecondary.setBody(content.optString("body"));
            }//  w ww.j  av  a2 s  . co m
        }

        // Set SmallIcons
        Bitmap icon1 = null;
        if (!options.secondaryIcon1Path.equals("")) {
            icon1 = getIconBitmap(mContext, "file://" + options.secondaryIcon1Path);
        }
        SrnImageAsset smallIcon1 = new SrnImageAsset(mContext, "smallIcon1", icon1);
        stdSecondary.setSmallIcon1(smallIcon1, options.secondaryIcon1Text);

        Bitmap icon2 = null;
        if (!options.secondaryIcon2Path.equals("")) {
            icon2 = getIconBitmap(mContext, "file://" + options.secondaryIcon2Path);
        }
        SrnImageAsset smallIcon2 = new SrnImageAsset(mContext, "smallIcon2", icon2);
        stdSecondary.setSmallIcon2(smallIcon2, options.secondaryIcon2Text);

        // Set Image
        if (!options.secondaryImage.equals("")) {
            Bitmap secBgBit = getIconBitmap(mContext, "file://" + options.secondaryImage);
            SrnImageAsset secBgAsst = new SrnImageAsset(mContext, "SecondaryBG", secBgBit);
            stdSecondary.setImage(secBgAsst);
        }

        secondaryTemplate = stdSecondary;

    } //In case of Seconday Type QR
    else if (options.secondaryType.equalsIgnoreCase(RichNotificationHelper.SECONDARY_TYPE_QR)) {
        SrnQRSecondaryTemplate qrSecondary = new SrnQRSecondaryTemplate();

        if (options.secondaryContent != null) {
            for (int i = 0; i < options.secondaryContent.length(); i++) {
                JSONObject content = options.secondaryContent.optJSONObject(i);
                if (content == null)
                    continue;
                qrSecondary.addListItem(content.optString("title"), content.optString("body"));
            }
        }

        // Set SmallIcons
        Bitmap icon1 = null;
        if (!options.secondaryIcon1Path.equals("")) {
            icon1 = getIconBitmap(mContext, "file://" + options.secondaryIcon1Path);
        }
        SrnImageAsset smallIcon1 = new SrnImageAsset(mContext, "smallIcon1", icon1);
        qrSecondary.setSmallIcon1(smallIcon1, options.secondaryIcon1Text);

        Bitmap icon2 = null;
        if (!options.secondaryIcon2Path.equals("")) {
            icon2 = getIconBitmap(mContext, "file://" + options.secondaryIcon2Path);
        }
        SrnImageAsset smallIcon2 = new SrnImageAsset(mContext, "smallIcon2", icon2);
        qrSecondary.setSmallIcon2(smallIcon2, options.secondaryIcon2Text);

        // Set Image
        if (!options.secondaryImage.equals("")) {
            Bitmap secBgBit = getIconBitmap(mContext, "file://" + options.secondaryImage);
            SrnImageAsset secBgAsst = new SrnImageAsset(mContext, "SecondaryBG", secBgBit);
            qrSecondary.setImage(secBgAsst);
        }

        secondaryTemplate = qrSecondary;
    } else {
        return null;
    }

    // Set the background color of the secondary template
    if (!options.secondaryBackgroundColor.isEmpty()) {
        try {
            int color = Color.parseColor(options.secondaryBackgroundColor);
            secondaryTemplate.setBackgroundColor(color);
        } catch (IllegalArgumentException illArgEx) {
            Log.e(TAG, "Invalid color string for Secondary Background");
        }
    } else {
        Log.e(TAG, "Empty string for Secondary Background");
    }

    return secondaryTemplate;
}

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  ww. j  ava 2 s.  c o  m*/
            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:net.zorgblub.typhon.CustomOPDSSite.java

public static CustomOPDSSite fromJSON(JSONObject json) throws JSONException {
    CustomOPDSSite site = new CustomOPDSSite();
    site.setUrl(json.getString("url"));
    site.setName(json.getString("name"));

    site.setDescription(json.optString("description"));
    site.setUserName(json.optString("userName"));
    site.setPassword(json.optString("password"));

    return site;// ww w .  j a v a  2  s  .c o  m
}

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

public static Favorite parse(JSONObject jsonObject) {
    if (null == jsonObject) {
        return null;
    }/*  w  w w.  j  a  v a  2 s  .com*/

    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:com.android.launcher2.InstallShortcutReceiver.java

private static ArrayList<PendingInstallShortcutInfo> getAndClearInstallQueue(SharedPreferences sharedPrefs) {
    synchronized (sLock) {
        Set<String> strings = sharedPrefs.getStringSet(APPS_PENDING_INSTALL, null);
        if (strings == null) {
            return new ArrayList<PendingInstallShortcutInfo>();
        }//from   ww w  .  j ava  2 s  .  c o  m
        ArrayList<PendingInstallShortcutInfo> infos = new ArrayList<PendingInstallShortcutInfo>();
        for (String json : strings) {
            try {
                JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
                Intent data = Intent.parseUri(object.getString(DATA_INTENT_KEY), 0);
                Intent launchIntent = Intent.parseUri(object.getString(LAUNCH_INTENT_KEY), 0);
                String 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);
                }
                data.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launchIntent);
                PendingInstallShortcutInfo info = new PendingInstallShortcutInfo(data, name, launchIntent);
                infos.add(info);
            } catch (org.json.JSONException e) {
                Log.d("InstallShortcutReceiver", "Exception reading shortcut to add: " + e);
            } catch (java.net.URISyntaxException e) {
                Log.d("InstallShortcutReceiver", "Exception reading shortcut to add: " + e);
            }
        }
        sharedPrefs.edit().putStringSet(APPS_PENDING_INSTALL, new HashSet<String>()).commit();
        return infos;
    }
}

From source file:com.citrus.sdk.CitrusUser.java

public static CitrusUser fromJSONObject(JSONObject response) {
    CitrusUser user = null;/*w  w w  . j a va  2  s  . com*/

    if (response != null) {
        String email = response.optString("email");
        String mobileNo = response.optString("mobileNo");
        String firstName = response.optString("firstName");
        String lastName = response.optString("lastName");
        Address address = Address.fromJSONObject(response);

        user = new CitrusUser(email, mobileNo, firstName, lastName, address);
    }

    return user;
}

From source file:com.chaosinmotion.securechat.server.commands.ChangePassword.java

public static boolean processRequest(Login.UserInfo userinfo, JSONObject requestParams, String token)
        throws ClassNotFoundException, SQLException, IOException {
    String oldpassword = requestParams.optString("oldpassword");
    String newpassword = requestParams.optString("newpassword");

    /*/*from  w  w w. ja  v  a  2s.  c  o  m*/
     * Validate the old password against the token we received
     */

    Connection c = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
        c = Database.get();
        ps = c.prepareStatement("SELECT password " + "FROM Users " + "WHERE userid = ?");
        ps.setInt(1, userinfo.getUserID());
        rs = ps.executeQuery();

        if (rs.next()) {
            /*
             * If the result is found, hash the entry in the way it would
             * be hashed by the front end, and compare to see if the
             * hash codes match. (This requires that the hashed password
             * stored in the back-end has a consistent capitalization.
             * We arbitrarily pick lower-case for our SHA-256 hex string.
             */
            String spassword = rs.getString(1);

            /*
             * Encrypt password with token and salt
             */

            spassword = spassword + Constants.SALT + token;
            spassword = Hash.sha256(spassword);

            /*
             * Compare; if matches, then return the user info record
             * so we can store away. While the SHA256 process returns
             * consistent case, we compare ignoring case anyway, just
             * because. :-)
             */

            if (!spassword.equalsIgnoreCase(oldpassword)) {
                /* Wrong password */
                return false;
            }
        }

        /*
         * Update password stored with the updated value passed in.
         */

        rs.close();
        ps.close();

        ps = c.prepareStatement("UPDATE Users " + "SET password = ? " + "WHERE userid = ?");
        ps.setString(1, newpassword);
        ps.setInt(2, userinfo.getUserID());
        ps.execute();

        return true;
    } finally {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
        if (c != null)
            c.close();
    }
}