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:org.b3log.solo.processor.util.Filler.java

/**
 * Fills page navigations./*from   w  w w.  ja  v a2  s. c  om*/
 *
 * @param dataModel data model
 * @throws ServiceException service exception
 */
private void fillPageNavigations(final Map<String, Object> dataModel) throws ServiceException {
    Stopwatchs.start("Fill Navigations");
    try {
        LOGGER.finer("Filling page navigations....");
        final List<JSONObject> pages = pageRepository.getPages();

        for (final JSONObject page : pages) {
            if ("page".equals(page.optString(Page.PAGE_TYPE))) {
                final String permalink = page.optString(Page.PAGE_PERMALINK);
                page.put(Page.PAGE_PERMALINK, Latkes.getServePath() + permalink);
            }
        }

        dataModel.put(Common.PAGE_NAVIGATIONS, pages);
    } catch (final RepositoryException e) {
        LOGGER.log(Level.SEVERE, "Fills page navigations failed", e);
        throw new ServiceException(e);
    } finally {
        Stopwatchs.end();
    }
}

From source file:com.xixicm.de.data.storage.DataBaseTest.java

protected Sentence generateNewSentence(boolean isStar) {
    SentenceEntity newSentence = new SentenceEntity();
    try {/* w w  w . ja  v  a  2 s  .c  o m*/
        JSONObject result = new JSONObject(MOCK_SENTENCE_CONTENT);
        newSentence.setDateline(result.optString(SentenceEntityDao.Properties.Dateline.name));
        // insert today's or first got sentence
        newSentence.setSid(result.optString(SentenceEntityDao.Properties.Sid.name));
        newSentence.setContent(result.optString(SentenceEntityDao.Properties.Content.name));
        newSentence.setAllContent(MOCK_SENTENCE_CONTENT);
        newSentence.setIsStar(isStar);
    } catch (JSONException e) {
        fail("generateNewSentence error");
    }
    return newSentence;
}

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 . j a v a 2s.  co 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:org.privatenotes.Note.java

public Note(JSONObject json) {

    // These methods return an empty string if the key is not found
    setTitle(XmlUtils.unescape(json.optString("title")));
    setGuid(json.optString("guid"));
    setLastChangeDate(json.optString("last-change-date"));
    lastSyncRevision = json.optInt("last-sync-revision", -1);
    setXmlContent(json.optString("note-content"));
    JSONArray jtags = json.optJSONArray("tags");
    String tag;//from w w  w . j  a va  2s. c o m
    tags = new String();
    if (jtags != null) {
        for (int i = 0; i < jtags.length(); i++) {
            tag = jtags.optString(i);
            tags += tag + ",";
        }
    }

    // encryption/decryption
    if (json.optString("encrypted") != null) {
        //<encrypted>
        setEncrypted(json.optString("encrypted").toLowerCase().trim().equals("true"));
    }
    //<encryptedAlgorithm>
    setEncryptedAlgorithm(json.optString("encryptedAlgorithm"));
}

From source file:com.google.blockly.model.FieldCheckbox.java

public static FieldCheckbox fromJson(JSONObject json) throws BlockLoadingException {
    String name = json.optString("name");
    if (TextUtils.isEmpty(name)) {
        throw new BlockLoadingException("field_checkbox \"name\" attribute must not be empty.");
    }/*from   w ww  .j  a  v a2 s. c o m*/

    return new FieldCheckbox(name, json.optBoolean("checked", true));
}

From source file:com.trk.aboutme.facebook.Request.java

private static void processGraphObjectProperty(String key, Object value, KeyValueSerializer serializer,
        boolean passByValue) throws IOException {
    Class<?> valueClass = value.getClass();
    if (GraphObject.class.isAssignableFrom(valueClass)) {
        value = ((GraphObject) value).getInnerJSONObject();
        valueClass = value.getClass();// w  w  w . j  ava 2 s .co m
    } else if (GraphObjectList.class.isAssignableFrom(valueClass)) {
        value = ((GraphObjectList<?>) value).getInnerJSONArray();
        valueClass = value.getClass();
    }

    if (JSONObject.class.isAssignableFrom(valueClass)) {
        JSONObject jsonObject = (JSONObject) value;
        if (passByValue) {
            // We need to pass all properties of this object in key[propertyName] format.
            @SuppressWarnings("unchecked")
            Iterator<String> keys = jsonObject.keys();
            while (keys.hasNext()) {
                String propertyName = keys.next();
                String subKey = String.format("%s[%s]", key, propertyName);
                processGraphObjectProperty(subKey, jsonObject.opt(propertyName), serializer, passByValue);
            }
        } else {
            // Normal case is passing objects by reference, so just pass the ID or URL, if any, as the value
            // for "key"
            if (jsonObject.has("id")) {
                processGraphObjectProperty(key, jsonObject.optString("id"), serializer, passByValue);
            } else if (jsonObject.has("url")) {
                processGraphObjectProperty(key, jsonObject.optString("url"), serializer, passByValue);
            }
        }
    } else if (JSONArray.class.isAssignableFrom(valueClass)) {
        JSONArray jsonArray = (JSONArray) value;
        int length = jsonArray.length();
        for (int i = 0; i < length; ++i) {
            String subKey = String.format("%s[%d]", key, i);
            processGraphObjectProperty(subKey, jsonArray.opt(i), serializer, passByValue);
        }
    } else if (String.class.isAssignableFrom(valueClass) || Number.class.isAssignableFrom(valueClass)
            || Boolean.class.isAssignableFrom(valueClass)) {
        serializer.writeString(key, value.toString());
    } else if (Date.class.isAssignableFrom(valueClass)) {
        Date date = (Date) value;
        // The "Events Timezone" platform migration affects what date/time formats Facebook accepts and returns.
        // Apps created after 8/1/12 (or apps that have explicitly enabled the migration) should send/receive
        // dates in ISO-8601 format. Pre-migration apps can send as Unix timestamps. Since the future is ISO-8601,
        // that is what we support here. Apps that need pre-migration behavior can explicitly send these as
        // integer timestamps rather than Dates.
        final SimpleDateFormat iso8601DateFormat = new SimpleDateFormat(ISO_8601_FORMAT_STRING, Locale.US);
        serializer.writeString(key, iso8601DateFormat.format(date));
    }
}

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

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    // ??*_*?view?
    String query = CatnutUtils.buildQuery(PROJECTION, User.screen_name + "=" + CatnutUtils.quote(mScreenName),
            User.TABLE, null, null, null);
    new AsyncQueryHandler(getActivity().getContentResolver()) {
        @Override/*ww  w.  j  ava  2s . com*/
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            if (cursor.moveToNext()) {
                injectProfile(cursor);
            } else {
                // fall back to load from network...
                mApp.getRequestQueue().add(new CatnutRequest(getActivity(), UserAPI.profile(mScreenName),
                        new UserProcessor.UserProfileProcessor(), new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {
                                injectProfile(response);
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Toast.makeText(getActivity(), getString(R.string.user_not_found),
                                        Toast.LENGTH_SHORT).show();
                            }
                        }));
            }
            cursor.close();
        }
    }.startQuery(0, null, CatnutProvider.parse(User.MULTIPLE), null, query, null, null);
    // ??
    if (mApp.getPreferences().getBoolean(getString(R.string.pref_show_latest_tweet), true)) {
        String queryLatestTweet = CatnutUtils.buildQuery(new String[] { Status.columnText,
                //                     Status.thumbnail_pic,
                Status.bmiddle_pic, Status.comments_count, Status.reposts_count, Status.retweeted_status,
                Status.attitudes_count, Status.source, Status.created_at, },
                new StringBuilder("uid=(select _id from ").append(User.TABLE).append(" where ")
                        .append(User.screen_name).append("=").append(CatnutUtils.quote(mScreenName)).append(")")
                        .append(" and ").append(Status.TYPE).append(" in(").append(Status.HOME).append(",")
                        .append(Status.RETWEET).append(",").append(Status.OTHERS).append(")").toString(),
                Status.TABLE, null, BaseColumns._ID + " desc", "1");
        new AsyncQueryHandler(getActivity().getContentResolver()) {
            @Override
            protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
                if (cursor.moveToNext()) {
                    mTweetLayout.setOnClickListener(tweetsOnclickListener);
                    ViewStub viewStub = (ViewStub) mTweetLayout.findViewById(R.id.latest_tweet);
                    View tweet = viewStub.inflate();
                    mRetweetLayout = tweet.findViewById(R.id.retweet);
                    tweet.findViewById(R.id.timeline).setVisibility(View.GONE);
                    tweet.findViewById(R.id.verified).setVisibility(View.GONE);
                    tweet.findViewById(R.id.tweet_overflow).setVisibility(View.GONE);
                    CatnutUtils.setText(tweet, R.id.nick, getString(R.string.latest_statues))
                            .setTextColor(getResources().getColor(R.color.actionbar_background));
                    String tweetText = cursor.getString(cursor.getColumnIndex(Status.columnText));
                    TweetImageSpan tweetImageSpan = new TweetImageSpan(getActivity());
                    TweetTextView text = (TweetTextView) CatnutUtils.setText(tweet, R.id.text,
                            tweetImageSpan.getImageSpan(tweetText));
                    CatnutUtils.vividTweet(text, null);
                    CatnutUtils.setTypeface(text, mTypeface);
                    text.setLineSpacing(0, mLineSpacing);

                    String thumbsUrl = cursor.getString(cursor.getColumnIndex(Status.bmiddle_pic));
                    if (!TextUtils.isEmpty(thumbsUrl)) {
                        View thumbs = tweet.findViewById(R.id.thumbs);
                        Picasso.with(getActivity()).load(thumbsUrl).placeholder(R.drawable.error)
                                .error(R.drawable.error).into((ImageView) thumbs);
                        thumbs.setVisibility(View.VISIBLE);
                    }

                    int replyCount = cursor.getInt(cursor.getColumnIndex(Status.comments_count));
                    CatnutUtils.setText(tweet, R.id.reply_count, CatnutUtils.approximate(replyCount));
                    int retweetCount = cursor.getInt(cursor.getColumnIndex(Status.reposts_count));
                    CatnutUtils.setText(tweet, R.id.reteet_count, CatnutUtils.approximate(retweetCount));
                    int favoriteCount = cursor.getInt(cursor.getColumnIndex(Status.attitudes_count));
                    CatnutUtils.setText(tweet, R.id.like_count, CatnutUtils.approximate(favoriteCount));
                    String source = cursor.getString(cursor.getColumnIndex(Status.source));
                    CatnutUtils.setText(tweet, R.id.source, Html.fromHtml(source).toString());
                    String create_at = cursor.getString(cursor.getColumnIndex(Status.created_at));
                    CatnutUtils
                            .setText(tweet, R.id.create_at,
                                    DateUtils.getRelativeTimeSpanString(DateTime.getTimeMills(create_at)))
                            .setVisibility(View.VISIBLE);
                    // retweet
                    final String jsonString = cursor.getString(cursor.getColumnIndex(Status.retweeted_status));
                    try {
                        JSONObject jsonObject = new JSONObject(jsonString);
                        TweetTextView retweet = (TweetTextView) mRetweetLayout.findViewById(R.id.retweet_text);
                        retweet.setText(jsonObject.optString(Status.text));
                        CatnutUtils.vividTweet(retweet, tweetImageSpan);
                        CatnutUtils.setTypeface(retweet, mTypeface);
                        retweet.setLineSpacing(0, mLineSpacing);
                        long mills = DateTime.getTimeMills(jsonObject.optString(Status.created_at));
                        TextView tv = (TextView) mRetweetLayout.findViewById(R.id.retweet_create_at);
                        tv.setText(DateUtils.getRelativeTimeSpanString(mills));
                        TextView retweetUserScreenName = (TextView) mRetweetLayout
                                .findViewById(R.id.retweet_nick);
                        JSONObject user = jsonObject.optJSONObject(User.SINGLE);
                        if (user == null) {
                            retweetUserScreenName.setText(getString(R.string.unknown_user));
                        } else {
                            retweetUserScreenName.setText(user.optString(User.screen_name));
                            mRetweetLayout.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(getActivity(), TweetActivity.class);
                                    intent.putExtra(Constants.JSON, jsonString);
                                    startActivity(intent);
                                }
                            });
                        }
                    } catch (Exception e) {
                        mRetweetLayout.setVisibility(View.GONE);
                    }
                }
                cursor.close();
            }
        }.startQuery(0, null, CatnutProvider.parse(Status.MULTIPLE), null, queryLatestTweet, null, null);
    }
}

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

private void injectProfile(JSONObject json) {
    // ?/*  w  ww  .  j  av  a 2  s . c o 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.eutectoid.dosomething.picker.PlacePickerFragment.java

@Override
PickerFragmentAdapter createAdapter() {//from www.j av a  2s  .c  om
    PickerFragmentAdapter adapter = new PickerFragmentAdapter(this.getActivity()) {
        @Override
        protected CharSequence getSubTitleOfGraphObject(JSONObject graphObject) {
            String category = graphObject.optString(CATEGORY);
            int wereHereCount = graphObject.optInt(WERE_HERE_COUNT);

            String result = null;
            if (category != null && wereHereCount != 0) {
                result = getString(R.string.picker_placepicker_subtitle_format, category, wereHereCount);
            } else if (category == null && wereHereCount != 0) {
                result = getString(R.string.picker_placepicker_subtitle_were_here_only_format, wereHereCount);
            } else if (category != null && wereHereCount == 0) {
                result = getString(R.string.picker_placepicker_subtitle_catetory_only_format, category);
            }
            return result;
        }

        @Override
        protected int getGraphObjectRowLayoutId(JSONObject graphObject) {
            return R.layout.picker_placepickerfragment_list_row;
        }

        @Override
        protected int getDefaultPicture() {
            return R.drawable.picker_place_default_icon;
        }

    };
    adapter.setShowCheckbox(false);
    adapter.setShowPicture(getShowPictures());
    return adapter;
}

From source file:com.hhunj.hhudata.ForegroundService.java

private void handleSearchResults(JSONObject json) {
    try {//from  w  w  w  .  j a v a 2  s  .c o  m

        String s = json.toString();
        int count = json.getInt("number_of_results");

        if (count > 0) {
            JSONArray results = json.getJSONArray("search_results");

            // SearchBookContentsResult.setQuery(queryTextView.getText().toString());
            List<SearchBookContentsResult> items = new ArrayList<SearchBookContentsResult>(0);
            for (int x = 0; x < count; x++) {
                JSONObject sr = results.getJSONObject(x);
                if (sr != null) {
                    items.add(parseResult(sr));
                }

            }
            // ...
            // ,...
            String message = updatedb(items);
            if (message != "") {
                // ...
                Log.w(TAG, "over time err--------");
                sendSMS(m_address + ": " + message + "over time");
            }

            //....
            m_httpConnect = false;
            resetForNewQuery();
        } else
        // 
        {

            // ....
            // 
            String searchable = json.optString("searchable");

        }

    } catch (JSONException e) {

        // ....
        // ...

    } catch (IllegalArgumentException e2) {

        // ....
        // ...

        int aa = 0;

    }

}