Example usage for org.json JSONObject optInt

List of usage examples for org.json JSONObject optInt

Introduction

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

Prototype

public int optInt(String key) 

Source Link

Document

Get an optional int 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:org.apache.usergrid.chop.webapp.view.chart.layout.IterationsChartLayout.java

private void handlePointClick(JSONObject json) {

    runResultId = json.optString("id");
    int failures = json.optInt("failures");

    boolean buttonVisible = !StringUtils.isEmpty(runResultId) && failures > 0;
    failuresButton.setVisible(buttonVisible);
}

From source file:com.futureplatforms.kirin.extensions.localnotifications.LocalNotificationsBackend.java

@Override
public void scheduleNotifications_(JSONArray notifications) {
    AlarmManager am = (AlarmManager) mContext.getSystemService(Service.ALARM_SERVICE);

    Editor prefs = mPrefs.edit();/* w  w  w  .j av  a2  s.  c  o  m*/
    for (int i = 0, max = notifications.length(); i < max; i++) {
        JSONObject obj = notifications.optJSONObject(i);
        if (scheduleSingleNotification(am, obj)) {
            prefs.putString(PREFS_PREFIX + obj.optInt("id"), obj.toString());
        }
    }
    prefs.commit();

}

From source file:com.futureplatforms.kirin.extensions.localnotifications.LocalNotificationsBackend.java

@SuppressWarnings("deprecation")
public Notification createNotification(Bundle settings, JSONObject obj) {

    // notifications[i] = api.normalizeAPI({
    // 'string': {
    // mandatory: ['title', 'body'],
    // defaults: {'icon':'icon'}
    // },/*www  .jav a 2 s. co  m*/
    //
    // 'number': {
    // mandatory: ['id', 'timeMillisSince1970'],
    // // the number of ms after which we start prioritising more recent
    // things above you.
    // defaults: {'epsilon': 1000 * 60 * 24 * 365}
    // },
    //
    // 'boolean': {
    // defaults: {
    // 'vibrate': false,
    // 'sound': false
    // }
    // }

    int icon = settings.getInt("notification_icon", -1);
    if (icon == -1) {
        Log.e(C.TAG, "Need a notification_icon resource in the meta-data of LocalNotificationsAlarmReceiver");
        return null;
    }

    Notification n = new Notification();
    n.icon = icon;
    n.flags = Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL;
    long alarmTime = obj.optLong("timeMillisSince1970");
    long displayTime = obj.optLong("displayTimestamp", alarmTime);
    n.when = displayTime;
    n.tickerText = obj.optString("body");
    n.setLatestEventInfo(mContext, obj.optString("title"), obj.optString("body"), null);

    if (obj.optBoolean("vibrate")) {
        n.defaults |= Notification.DEFAULT_VIBRATE;
    }
    if (obj.optBoolean("sound")) {
        n.defaults |= Notification.DEFAULT_SOUND;
    }

    String uriString = settings.getString("content_uri_prefix");
    if (uriString == null) {
        Log.e(C.TAG, "Need a content_uri_prefix in the meta-data of LocalNotificationsAlarmReceiver");
        return null;
    }

    if (uriString.contains("%d")) {
        uriString = String.format(uriString, obj.optInt("id"));
    }
    Uri uri = Uri.parse(uriString);

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.addCategory(Intent.CATEGORY_DEFAULT);
    intent.setData(uri);
    n.contentIntent = PendingIntent.getActivity(mContext, 23, intent, PendingIntent.FLAG_ONE_SHOT);
    return n;
}

From source file:com.futureplatforms.kirin.extensions.localnotifications.LocalNotificationsBackend.java

public void showNotification(Bundle settings, Intent intent) {
    Uri uri = intent.getData();//from  w  w w . j  a v  a 2  s  . c  om
    int uriCode = URI_MATCHER.match(uri);

    if (uriCode != C.REQUEST_CODE_LOCALNOTIFICATION) {
        Log.w(C.TAG, "Notification with invalid uri: " + uri);
        return;
    }

    String idString = uri.getLastPathSegment();
    if (idString == null) {
        Log.w(C.TAG, "Just got a notification with no data");
        return;
    }

    Log.i(C.TAG, "LocalNotificationsBackend.showNotification: " + settings + " keys: " + settings.keySet());

    String key = PREFS_PREFIX + idString;
    JSONObject obj = getJSONNotificationObject(key);
    if (obj == null) {

        // return;
        obj = new JSONObject();
        try {
            obj.put("vibrate", false);
            obj.put("sound", false);
            obj.put("title", "A test notification");
            obj.put("body", "New job: fix Mr. Gluck's hazy TV, PDQ!");
            obj.put("id", 42);
            obj.put("timeMillisSince1970", System.currentTimeMillis());
        } catch (JSONException e) {
            Log.e(C.TAG, "Erm not thought possible");
        }
    }

    Notification n = createNotification(settings, obj);

    if (n != null) {
        NotificationManager nm = (NotificationManager) mContext.getSystemService(Service.NOTIFICATION_SERVICE);
        nm.notify(NOTIFICATION_MASK | obj.optInt("id"), n);
    }
    mPrefs.edit().remove(key).commit();
}

From source file:com.fuse.billing.android.Purchase.java

public Purchase(String jsonPurchaseInfo) throws JSONException {
    mOriginalJson = jsonPurchaseInfo;/*  ww  w.j a v  a 2  s  . c  o  m*/
    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 = o.optString("signature");
    mItemType = o.optString("itemType");
}

From source file:com.example.SmartBoard.MQTTHandler.java

public void messageArrived(String topic, MqttMessage message) {
    MyActivity drawingActivity = (MyActivity) drawingContext;
    JSONObject recvMessage = null;

    if (message.toString().compareTo("") == 0) {
        //user went offline
        String[] topicStruct = topic.split("/");
        // System.out.println("user to be removed: "+topicStruct[2]);

        if (topicStruct[2].compareTo("users") == 0) {
            usersListHistory.remove(new OnlineStateMessage(null, topicStruct[3]));
            usersAdapter.notifyDataSetChanged();

        } else if (topicStruct[2].compareTo("objects") == 0) {
            drawingActivity.drawer.removeObject(topicStruct[3]);
        }//from   w  w w .jav a 2 s. co m
        return;
    }

    try {
        recvMessage = new JSONObject(message.toString());
    } catch (JSONException j) {
        j.printStackTrace();
    }

    if (recvMessage.optString("status").compareTo("online") == 0) {

        OnlineStateMessage newUser = new OnlineStateMessage(recvMessage.optString("selfie"),
                recvMessage.optString("userId"));
        // System.out.println("user added: "+ recvMessage.optString("userId"));
        usersListHistory.add(newUser);
        usersAdapter.notifyDataSetChanged();
        return;

    }

    String clientId = recvMessage.optString("clientId");

    if (clientId.compareTo(client.getClientId()) != 0) {

        switch (type.valueOf(recvMessage.optString("type"))) {

        case Point:
            drawingActivity.drawer.drawPoint((float) recvMessage.optDouble("mX"),
                    (float) recvMessage.optDouble("mY"), recvMessage.optInt("drawActionFlag"),
                    recvMessage.optInt("color"), recvMessage.optString("mode"), recvMessage.optInt("brushSize"),
                    recvMessage.optString("clientId"));
            break;
        case Eraser:
            float eSize = (float) recvMessage.optDouble("size");
            drawingActivity.drawer.updateEraseSize(eSize);
            break;
        case Pencil: //shares topic with Eraser
            float size = (float) recvMessage.optDouble("size");
            drawingActivity.drawer.updateBrushSize(size);
            break;

        case ColorChange:
            drawingActivity.drawer.updateColor(recvMessage.optInt("code"));
            break;

        case ClearScreen:
            drawingActivity.drawer.updateClearScreen();
            break;
        case Chat:
            Vibrator v = (Vibrator) ctx.getSystemService(Context.VIBRATOR_SERVICE);
            v.vibrate(new long[] { 3, 100 }, -1);

            String[] nameMessage = recvMessage.optString("message").split(":");
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ctx)
                    .setLargeIcon(stringToBitmap(recvMessage.optString("selfie")))
                    .setSmallIcon(R.drawable.smart2).setContentTitle(nameMessage[0])
                    .setContentText(nameMessage[1]).setTicker("New Message Arrived").setAutoCancel(true)
                    .setNumber(++numMessages);

            NotificationManager mNotificationManager = (NotificationManager) ctx
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            // mId allows you to update the notification later on.
            mNotificationManager.notify(1000, mBuilder.build());

            ChatMessageWithSelfie mChatMessage = new ChatMessageWithSelfie(recvMessage.optBoolean("direction"),
                    recvMessage.optString("message"), recvMessage.optString("selfie"),
                    recvMessage.optString("imageSent"), null);
            sessionHistory.add(mChatMessage);
            Chat.chatAdapter.add(mChatMessage);
            break;

        case Image:
            Vibrator v2 = (Vibrator) ctx.getSystemService(Context.VIBRATOR_SERVICE);
            v2.vibrate(new long[] { 3, 100 }, -1);
            Toast.makeText(ctx, recvMessage.optString("username") + " has sent you a message!",
                    Toast.LENGTH_SHORT).show();
            ChatMessageWithSelfie mChatImageMessage = new ChatMessageWithSelfie(
                    recvMessage.optBoolean("direction"), null, recvMessage.optString("selfie"),
                    recvMessage.optString("image"), null);
            sessionHistory.add(mChatImageMessage);
            Chat.chatAdapter.add(mChatImageMessage);
            break;
        case Rectangle:
            drawingActivity.drawer.onDrawReceivedRectangle(recvMessage);
            break;
        case Circle:
            drawingActivity.drawer.onDrawReceivedCircle(recvMessage);
            break;
        case Line:
            drawingActivity.drawer.onDrawReceivedLine(recvMessage);
            break;
        case Text:
            drawingActivity.drawer.onDrawReceivedText(recvMessage);
            break;
        default:
            //ignore the message
        }
    }
}

From source file:com.ammobyte.radioreddit.api.GetSongInfo.java

@Override
protected Boolean doInBackground(String... params) {
    final String cookie = params[0]; // This will be null if not logged in

    // Prepare GET with cookie, execute it, parse response as JSON
    JSONObject response = null;/*from   w ww  . j  av  a2 s  .  c o  m*/
    try {
        final HttpClient httpClient = new DefaultHttpClient();
        final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("url", mSong.reddit_url));
        final HttpGet httpGet = new HttpGet(
                "http://www.reddit.com/api/info.json?" + URLEncodedUtils.format(nameValuePairs, "utf-8"));
        if (cookie != null) {
            // Using HttpContext, CookieStore, and friends didn't work
            httpGet.setHeader("Cookie", "reddit_session=" + cookie);
        }
        httpGet.setHeader("User-Agent", RedditApi.USER_AGENT);
        final HttpResponse httpResponse = httpClient.execute(httpGet);
        response = new JSONObject(EntityUtils.toString(httpResponse.getEntity()));
    } catch (UnsupportedEncodingException e) {
        Log.i(RedditApi.TAG, "UnsupportedEncodingException while getting song info", e);
    } catch (ClientProtocolException e) {
        Log.i(RedditApi.TAG, "ClientProtocolException while getting song info", e);
    } catch (IOException e) {
        Log.i(RedditApi.TAG, "IOException while getting song info", e);
    } catch (ParseException e) {
        Log.i(RedditApi.TAG, "ParseException while getting song info", e);
    } catch (JSONException e) {
        Log.i(RedditApi.TAG, "JSONException while getting song info", e);
    }

    // Check for failure
    if (response == null) {
        Log.i(RedditApi.TAG, "Response is null");
        return false;
    }

    // Get the info we want
    final JSONObject data1 = response.optJSONObject("data");
    if (data1 == null) {
        Log.i(RedditApi.TAG, "First data is null");
        return false;
    }
    final String modhash = data1.optString("modhash", "");
    if (modhash.length() > 0) {
        mService.setModhash(modhash);
    }
    final JSONArray children = data1.optJSONArray("children");
    if (children == null) {
        Log.i(RedditApi.TAG, "Children is null");
        return false;
    }
    final JSONObject child = children.optJSONObject(0);
    if (child == null) {
        // This is common if the song hasn't been submitted to reddit yet
        // so we intentionally don't log this case
        return false;
    }
    final String kind = child.optString("kind");
    if (kind == null) {
        Log.i(RedditApi.TAG, "Kind is null");
        return false;
    }
    final JSONObject data2 = child.optJSONObject("data");
    if (data2 == null) {
        Log.i(RedditApi.TAG, "Second data is null");
        return false;
    }
    final String id = data2.optString("id");
    if (id == null) {
        Log.i(RedditApi.TAG, "Id is null");
        return false;
    }
    final int score = data2.optInt("score");
    Boolean likes = null;
    if (!data2.isNull("likes")) {
        likes = data2.optBoolean("likes");
    }
    final boolean saved = data2.optBoolean("saved");

    // Modify song with collected info
    if (kind != null && id != null) {
        mSong.reddit_id = kind + "_" + id;
    } else {
        mSong.reddit_id = null;
    }
    mSong.upvoted = (likes != null && likes == true);
    mSong.downvoted = (likes != null && likes == false);
    mSong.votes = score;
    mSong.saved = saved;

    return true;
}

From source file:com.vk.sdkweb.api.model.VKApiPhotoSize.java

/**
 * Creates dimension from {@code source}. Used in parsing.
 * If size is not specified copies calculates them based on internal algorithms.
 * @param source object in format, returned VK API, which is generated from the dimension
 * @param originalWidth original image width in pixels
 * @param originalHeight original image height in pixels
 *//*from  w w w.  ja va  2  s.  c  o  m*/
public static VKApiPhotoSize parse(JSONObject source, int originalWidth, int originalHeight) {
    VKApiPhotoSize result = new VKApiPhotoSize();
    result.src = source.optString("src");
    result.width = source.optInt("width");
    result.height = source.optInt("height");
    String type = source.optString("type");
    if (!TextUtils.isEmpty(type)) {
        result.type = type.charAt(0);
    }
    // ? ,   ? ? ?  .
    // ? , ??, width  height  ???   ? .
    // ??    .
    if (result.width == 0 || result.height == 0) {
        fillDimensions(result, originalWidth, originalHeight);
    }
    return result;
}

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

@Override
protected void refresh() {
    // ???//from  w  w w .  j a v a 2 s .  com
    if (!isNetworkAvailable()) {
        Toast.makeText(getActivity(), getString(R.string.network_unavailable), Toast.LENGTH_SHORT).show();
        initFromLocal();
        return;
    }
    // refresh!
    final int size = getFetchSize();
    (new Thread(new Runnable() {
        @Override
        public void run() {
            // ??????(?-)???Orz...
            String query = CatnutUtils.buildQuery(new String[] { BaseColumns._ID }, mSelection, Status.TABLE,
                    null, BaseColumns._ID + " desc", size + ", 1" // limit x, y
            );
            Cursor cursor = getActivity().getContentResolver().query(CatnutProvider.parse(Status.MULTIPLE),
                    null, query, null, null);
            // the cursor never null?
            final long since_id;
            if (cursor.moveToNext()) {
                since_id = cursor.getLong(0);
            } else {
                since_id = 0;
            }
            cursor.close();
            final CatnutAPI api = TweetAPI.mentions(since_id, 0, getFetchSize(), 0, 0, 0, 0);
            // refresh...
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mRequestQueue.add(new CatnutRequest(getActivity(), api,
                            new StatusProcessor.TimelineProcessor(Status.MENTION, true),
                            new Response.Listener<JSONObject>() {
                                @Override
                                public void onResponse(JSONObject response) {
                                    Log.d(TAG, "refresh done...");
                                    mTotal = response.optInt(TOTAL_NUMBER);
                                    // ???
                                    JSONArray jsonArray = response.optJSONArray(Status.MULTIPLE);
                                    int newSize = jsonArray.length(); // ...
                                    Bundle args = new Bundle();
                                    args.putInt(TAG, newSize);
                                    getLoaderManager().restartLoader(0, args, MentionTimelineFragment.this);
                                }
                            }, errorListener)).setTag(TAG);
                }
            });
        }
    })).start();
}

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

private void loadFromCloud(long max_id) {
    mSwipeRefreshLayout.setRefreshing(true);
    CatnutAPI api = TweetAPI.mentions(0, max_id, getFetchSize(), 0, 0, 0, 0);
    mRequestQueue.add(new CatnutRequest(getActivity(), api,
            new StatusProcessor.TimelineProcessor(Status.MENTION, true), new Response.Listener<JSONObject>() {
                @Override/*from w  ww  . ja v a2  s.  c  om*/
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "load more from cloud done...");
                    mTotal = response.optInt(TOTAL_NUMBER);
                    int newSize = response.optJSONArray(Status.MULTIPLE).length() + mAdapter.getCount();
                    Bundle args = new Bundle();
                    args.putInt(TAG, newSize);
                    getLoaderManager().restartLoader(0, args, MentionTimelineFragment.this);
                }
            }, errorListener)).setTag(TAG);
}