Example usage for org.json JSONObject optLong

List of usage examples for org.json JSONObject optLong

Introduction

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

Prototype

public long optLong(String key) 

Source Link

Document

Get an optional long value associated with a key, or zero if there is no such key or if the value is not a number.

Usage

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

public Purchase(String itemType, String jsonPurchaseInfo, String signature) throws JSONException {
    mItemType = itemType;//from   w w w .j  av a  2  s . c  o m
    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));//  w ww  .  jav  a2  s  .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.cantwellcode.fitfriend.purchases.Purchase.java

public Purchase(String itemType, String jsonPurchaseInfo, String signature) throws JSONException {
    mItemType = itemType;/*from   w  w w  .ja  va  2 s.  c  o m*/
    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"));
    mSignature = signature;
}

From source file:br.com.indigo.android.facebook.SocialFacebook.java

private FbEvent parseEvent(JSONObject eventJson) throws JSONException {
    FbEvent event = new FbEvent();

    event.setId(eventJson.getString("id"));
    event.setName(eventJson.getString("name"));
    event.setDescription(eventJson.optString("description"));
    event.setStartTime(dateWithFacebookUnixTimestamp(eventJson.getLong("start_time")));
    event.setEndTime(dateWithFacebookUnixTimestamp(eventJson.optLong("end_time")));
    event.setLocation(eventJson.optString("location"));
    event.setPrivacy(eventJson.optString("privacy"));

    JSONObject ownerJson = eventJson.optJSONObject("owner");
    if (ownerJson != null) {
        FbSimpleUser owner = new FbSimpleUser();
        owner.setId(ownerJson.getString("id"));
        owner.setName(ownerJson.optString("name"));
        event.setOwner(owner);/*  w  w  w  . j av  a 2s  . c om*/
    }

    return event;
}

From source file:br.com.indigo.android.facebook.SocialFacebook.java

private void handleCommentsResponse(JSONObject jsonResponse, CommentsListener listener) {

    FbComment comment = null;//from ww w.  j a va  2s  .c om
    ArrayList<FbComment> comments = new ArrayList<FbComment>();

    try {
        JSONArray objs = jsonResponse.getJSONArray("data");

        for (int i = 0; i < objs.length(); i++) {
            JSONObject obj = objs.getJSONObject(i);

            comment = new FbComment();
            comment.setId(obj.getString("id"));
            comment.setMessage(obj.optString("message"));
            comment.setCreatedTime(new Date(obj.optLong("created_time") * 1000));
            comment.setNumberOfLikes(obj.optInt("likes"));

            JSONObject fromJson = obj.optJSONObject("from");
            if (fromJson != null) {
                FbSimpleUser fromUser = new FbSimpleUser();
                fromUser.setId(fromJson.getString("id"));
                fromUser.setName(fromJson.optString("name"));

                comment.setFrom(fromUser);
            }

            comments.add(comment);
        }

        String nextPage = null;
        JSONObject paging = jsonResponse.optJSONObject("paging");
        if (paging != null) {
            nextPage = paging.optString("next");
        }

        listener.onComplete(comments, nextPage);

    } catch (JSONException e) {
        Util.logd(TAG, "Could not parse Json response", e);
        listener.onFail(e);
    }
}

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

private void injectProfile(JSONObject json) {
    // ?// w ww. j  a  va  2 s  .  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.aniruddhc.acemusic.player.GMusicHelpers.WebClientPlaylistsSchema.java

@Override
public WebClientPlaylistsSchema fromJsonObject(JSONObject jsonObject) {
    if (jsonObject != null) {
        mTitle = jsonObject.optString("title", null);
        mPlaylistId = jsonObject.optString("playlistId", null);
        mRequestTime = jsonObject.optLong("requestTime");
        mContinuationToken = jsonObject.optString("continuationToken", null);
        mDifferentialUpdate = jsonObject.optBoolean("differentialUpdate");
        mContinuation = jsonObject.optBoolean("continuation");

        JSONArray songsArray = jsonObject.optJSONArray("playlist");
        mPlaylist = fromJsonArray(songsArray);
    }//  w  w w . java 2s .c  om

    //This method returns itself to support chaining.
    return this;
}

From source file:edu.stanford.mobisocial.dungbeetle.MessagingManagerThread.java

private void handleIncomingMessage(final IncomingMessage incoming) {
    final SignedObj contents = incoming.contents();
    final long hash = contents.getHash();
    if (contents.getSender() == null) {
        Log.e(TAG, "Null sender for " + contents.getType() + ", " + contents.getJson());
        return;/*from ww w  .j  a v  a2  s . c om*/
    }
    final String personId = contents.getSender().getId();
    // final String personId = incoming.from();

    /**
     * TODO: This needs to be updated with the POSI standards to accept a
     * SignedObj.
     */

    if (DBG)
        Log.i(TAG, "Localized contents: " + contents);
    try {
        JSONObject in_obj = contents.getJson();
        String feedName = contents.getFeedName();
        String type = contents.getType();
        Uri feedPreUri = Feed.uriForName(feedName);
        if (mMessageDropHandler.preFiltersObj(mContext, feedPreUri)) {
            return;
        }

        if (mHelper.queryAlreadyReceived(hash)) {
            if (DBG)
                Log.i(TAG, "Message already received: " + hash);
            return;
        }

        Maybe<Contact> contact = mHelper.contactForPersonId(personId);
        final DbEntryHandler objHandler = DbObjects.getObjHandler(in_obj);
        byte[] extracted_data = null;
        if (objHandler instanceof UnprocessedMessageHandler) {
            Pair<JSONObject, byte[]> r = ((UnprocessedMessageHandler) objHandler).handleUnprocessed(mContext,
                    in_obj);
            if (r != null) {
                in_obj = r.first;
                extracted_data = r.second;
            }
        }
        final JSONObject obj = in_obj;
        final byte[] raw = extracted_data;

        /**
         *  TODO STFAN BJDODSON KANAKB
         *
         *  See FriendAcceptObj.handleUnprocessed as template, code is something like:
         *
         *  if (!mPublicKeyDirectory.verify(in_obj.getString("email"), in_obj.getPublicKey())) {
         *    Log.w("Spammer trying to claim public key for email address");
         *    return;
         *  }
         *  if (inAddressBook(email)) {
         *     // auto-accept and notify of new friend
         *  } else {
         *     // notification to accept friend
         *  }
         */

        if (!contact.isKnown()) {
            Log.i(TAG, "Message from unknown contact. " + contents);
            return;
        }

        /**
         * Run handlers over all received objects:
         */

        long objId;
        final Contact realContact = contact.get();
        long contactId = realContact.id;
        if (DBG)
            Log.d(TAG, "Msg from " + contactId + " ( " + realContact.name + ")");
        // Insert into the database. (TODO: Handler, both android.os and
        // musubi.core)

        if (!objHandler.handleObjFromNetwork(mContext, realContact, obj)) {
            return;
        }

        Integer intKey = null;
        if (obj.has(DbObjects.JSON_INT_KEY)) {
            intKey = obj.getInt(DbObjects.JSON_INT_KEY);
            obj.remove(DbObjects.JSON_INT_KEY);
        }
        objId = mHelper.addObjectByJson(contact.otherwise(Contact.NA()).id, obj, hash, raw, intKey);
        Uri feedUri;
        if (feedName.equals("friend")) {
            feedUri = Feed.uriForName("friend/" + contactId);
        } else {
            feedUri = Feed.uriForName(feedName);
        }
        mContext.getContentResolver().notifyChange(feedUri, null);
        if (feedName.equals("direct") || feedName.equals("friend")) {
            long time = obj.optLong(DbObject.TIMESTAMP);
            Helpers.updateLastPresence(mContext, realContact, time);
            objHandler.handleDirectMessage(mContext, realContact, obj);
        }

        /**
         * Run handlers over all received objects:
         */

        // TODO: framework code.
        DbObj signedObj = App.instance().getMusubi().objForId(objId);
        getFromNetworkHandlers().handleObj(mContext, DbObjects.forType(type), signedObj);
        objHandler.afterDbInsertion(mContext, signedObj);
    } catch (Exception e) {
        Log.e(TAG, "Error handling incoming message.", e);
    }
}

From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java

/**
 * Inserts an object into the database and flags it to be sent by
 * the transport layer.// w  ww .  ja v  a2  s.co  m
 */
long addToFeed(String appId, String feedName, ContentValues values) {
    try {
        JSONObject json = new JSONObject(values.getAsString(DbObject.JSON));
        String type = values.getAsString(DbObject.TYPE);

        long nextSeqId = getFeedMaxSequenceId(Contact.MY_ID, feedName) + 1;
        long timestamp = new Date().getTime();
        json.put(DbObjects.TYPE, type);
        json.put(DbObjects.FEED_NAME, feedName);
        json.put(DbObjects.SEQUENCE_ID, nextSeqId);
        json.put(DbObjects.TIMESTAMP, timestamp);
        json.put(DbObjects.APP_ID, appId);

        // Explicit column referencing avoids database errors.
        ContentValues cv = new ContentValues();
        cv.put(DbObject._ID, getNextId());
        cv.put(DbObject.APP_ID, appId);
        cv.put(DbObject.FEED_NAME, feedName);
        cv.put(DbObject.CONTACT_ID, Contact.MY_ID);
        cv.put(DbObject.TYPE, type);
        cv.put(DbObject.SEQUENCE_ID, nextSeqId);
        cv.put(DbObject.JSON, json.toString());
        cv.put(DbObject.TIMESTAMP, timestamp);
        cv.put(DbObject.LAST_MODIFIED_TIMESTAMP, new Date().getTime());

        if (values.containsKey(DbObject.RAW)) {
            cv.put(DbObject.RAW, values.getAsByteArray(DbObject.RAW));
        }
        if (values.containsKey(DbObject.KEY_INT)) {
            cv.put(DbObject.KEY_INT, values.getAsInteger(DbObject.KEY_INT));
        }
        if (json.has(DbObject.CHILD_FEED_NAME)) {
            cv.put(DbObject.CHILD_FEED_NAME, json.optString(DbObject.CHILD_FEED_NAME));
        }
        if (cv.getAsString(DbObject.JSON).length() > SIZE_LIMIT)
            throw new RuntimeException("Messasge size is too large for sending");
        Long objId = getWritableDatabase().insertOrThrow(DbObject.TABLE, null, cv);

        if (json.has(DbObjects.TARGET_HASH)) {
            long hashA = json.optLong(DbObjects.TARGET_HASH);
            long idA = objIdForHash(hashA);
            String relation;
            if (json.has(DbObjects.TARGET_RELATION)) {
                relation = json.optString(DbObjects.TARGET_RELATION);
            } else {
                relation = DbRelation.RELATION_PARENT;
            }
            if (idA == -1) {
                Log.e(TAG, "No objId found for hash " + hashA);
            } else {
                addObjRelation(idA, objId, relation);
            }
        }

        Uri objUri = DbObject.uriForObj(objId);
        mContext.getContentResolver().registerContentObserver(objUri, false,
                new ModificationObserver(mContext, objId));
        return objId;
    } catch (Exception e) {
        // TODO, too spammy
        //e.printStackTrace(System.err);
        return -1;
    }
}

From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java

long addObjectByJson(long contactId, JSONObject json, long hash, byte[] raw, Integer intKey) {
    try {//from   w ww  .ja  va2 s . c o m
        long objId = getNextId();
        long seqId = json.optLong(DbObjects.SEQUENCE_ID);
        long timestamp = json.getLong(DbObjects.TIMESTAMP);
        String feedName = json.getString(DbObjects.FEED_NAME);
        String type = json.getString(DbObjects.TYPE);
        String appId = json.getString(DbObjects.APP_ID);
        ContentValues cv = new ContentValues();
        cv.put(DbObject._ID, objId);
        cv.put(DbObject.APP_ID, appId);
        cv.put(DbObject.FEED_NAME, feedName);
        cv.put(DbObject.CONTACT_ID, contactId);
        cv.put(DbObject.TYPE, type);
        cv.put(DbObject.SEQUENCE_ID, seqId);
        cv.put(DbObject.JSON, json.toString());
        cv.put(DbObject.TIMESTAMP, timestamp);
        cv.put(DbObject.HASH, hash);
        cv.put(DbObject.SENT, 1);

        cv.put(DbObject.LAST_MODIFIED_TIMESTAMP, new Date().getTime());
        if (raw != null) {
            cv.put(DbObject.RAW, raw);
        }
        if (intKey != null) {
            cv.put(DbObject.KEY_INT, intKey);
        }

        // TODO: Deprecated!!
        if (json.has(DbObject.CHILD_FEED_NAME)) {
            cv.put(DbObject.CHILD_FEED_NAME, json.optString(DbObject.CHILD_FEED_NAME));
        }
        if (cv.getAsString(DbObject.JSON).length() > SIZE_LIMIT)
            throw new RuntimeException("Messasge size is too large for sending");
        long newObjId = getWritableDatabase().insertOrThrow(DbObject.TABLE, null, cv);

        String notifyName = feedName;
        if (json.has(DbObjects.TARGET_HASH)) {
            long hashA = json.optLong(DbObjects.TARGET_HASH);
            long idA = objIdForHash(hashA);
            notifyName = feedName + ":" + hashA;
            String relation;
            if (json.has(DbObjects.TARGET_RELATION)) {
                relation = json.optString(DbObjects.TARGET_RELATION);
            } else {
                relation = DbRelation.RELATION_PARENT;
            }
            if (idA == -1) {
                Log.e(TAG, "No objId found for hash " + hashA);
            } else {
                addObjRelation(idA, newObjId, relation);
            }
        }

        ContentResolver resolver = mContext.getContentResolver();
        DungBeetleContentProvider.notifyDependencies(this, resolver, notifyName);
        updateObjModification(App.instance().getMusubi().objForId(newObjId));
        return objId;
    } catch (Exception e) {
        if (DBG)
            Log.e(TAG, "Error adding object by json.", e);
        return -1;
    }
}