Example usage for org.json JSONObject getInt

List of usage examples for org.json JSONObject getInt

Introduction

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

Prototype

public int getInt(String key) throws JSONException 

Source Link

Document

Get the int value associated with a key.

Usage

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

@Override
public VKApiModel parse(JSONObject object) {
    try {/*from  ww  w  . ja  va 2s  .  co m*/
        JSONArray jsonArray;
        if ((jsonArray = object.optJSONArray("response")) == null) {
            object = object.getJSONObject("response");
            count = object.getInt("count");
            jsonArray = object.getJSONArray("items");
        }
        parse(jsonArray);

    } catch (JSONException e) {
        if (VKSdk.DEBUG)
            e.printStackTrace();
    }
    fields = object;
    return this;
}

From source file:produvia.com.scanner.DevicesActivity.java

/*********************************************************************
 * The WeaverSdk callback indicating that a task has been completed:
 *********************************************************************/
@Override// w  ww  .  j  av  a2s .com
public void onTaskCompleted(final int flag, final JSONObject response) {
    if (response == null || mActivityPaused)
        return;
    try {

        if (response.has("responseCode") && response.getInt("responseCode") == 401) {
            //unauthorized:
            runWelcomeActivity();
        }

        switch (flag) {
        case WeaverSdk.ACTION_USER_LOGOUT:
            runWelcomeActivity();
            break;

        case WeaverSdk.ACTION_SERVICES_GET:
            if (response.getBoolean("success")) {
                handleReceivedServices(response.getJSONObject("data"));
            }
            break;

        }

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

From source file:produvia.com.scanner.DevicesActivity.java

public void promptLogin(final JSONObject loginService, final JSONObject responseData) {

    runOnUiThread(new Runnable() {
        public void run() {
            try {
                String type = loginService.getString("type");
                //there was a login error. login again
                if (type.equals(WeaverSdk.FIRST_LOGIN_TYPE_NORMAL)) {
                    //prompt for username and password and retry:
                    promptUsernamePassword(loginService, responseData, false, null);

                } else if (type.equals(WeaverSdk.FIRST_LOGIN_TYPE_KEY)) {

                    promptUsernamePassword(loginService, responseData, true,
                            loginService.getString("description"));

                } else if (type.equals(WeaverSdk.FIRST_LOGIN_TYPE_PRESS2LOGIN)) {
                    //prompt for username and password and retry:
                    int countdown = loginService.has("login_timeout") ? loginService.getInt("login_timeout")
                            : 15;//from   ww  w . j a  va  2s.c  o m
                    final AlertDialog alertDialog = new AlertDialog.Builder(DevicesActivity.this).create();
                    alertDialog.setTitle(loginService.getString("description"));
                    alertDialog.setCancelable(false);
                    alertDialog.setCanceledOnTouchOutside(false);
                    alertDialog.setMessage(loginService.getString("description") + "\n"
                            + "Attempting to login again in " + countdown + " seconds...");
                    alertDialog.show(); //

                    new CountDownTimer(countdown * 1000, 1000) {
                        @Override
                        public void onTick(long millisUntilFinished) {
                            try {
                                alertDialog.setMessage(loginService.getString("description") + "\n"
                                        + "Attempting to login again in " + millisUntilFinished / 1000
                                        + " seconds...");
                            } catch (JSONException e) {

                            }
                        }

                        @Override
                        public void onFinish() {
                            alertDialog.dismiss();
                            new Thread(new Runnable() {
                                public void run() {

                                    try {
                                        JSONArray services = new JSONArray();
                                        services.put(loginService);
                                        responseData.put("services", services);
                                        WeaverSdkApi.servicesSet(DevicesActivity.this, responseData);
                                    } catch (JSONException e) {

                                    }
                                }
                            }).start();

                        }
                    }.start();

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

        }

    });

}

From source file:com.ibm.iot.android.iotstarter.utils.MessageConductor.java

/**
 * Steer incoming MQTT messages to the proper activities based on their content.
 *
 * @param payload The log of the MQTT message.
 * @param topic The topic the MQTT message was received on.
 * @throws JSONException If the message contains invalid JSON.
 *//* w ww.ja  v  a2s . c  om*/
public void steerMessage(String payload, String topic) throws JSONException {
    Log.d(TAG, ".steerMessage() entered");
    JSONObject top = new JSONObject(payload);
    JSONObject d = top.getJSONObject("d");

    if (topic.contains(Constants.COLOR_EVENT)) {
        Log.d(TAG, "Color Event");
        int r = d.getInt("r");
        int g = d.getInt("g");
        int b = d.getInt("b");

        // alpha value received is 0.0 < a < 1.0 but Color.argb expects 0 < a < 255
        int alpha = (int) (d.getDouble("alpha") * 255.0);
        if ((r > 255 || r < 0) || (g > 255 || g < 0) || (b > 255 || b < 0) || (alpha > 255 || alpha < 0)) {
            return;
        }

        app.setColor(Color.argb(alpha, r, g, b));
        Intent actionIntent = new Intent(Constants.APP_ID + Constants.INTENT_IOT);
        actionIntent.putExtra(Constants.INTENT_DATA, Constants.COLOR_EVENT);
        context.sendBroadcast(actionIntent);

    } else if (topic.contains(Constants.FRE_EVENT)) {
        JSONObject topp = new JSONObject(payload);
        JSONObject dd = topp.getJSONObject("d");
        int frequency = dd.getInt("f");

        Log.d("MMM", "" + frequency);
        app.setFfe(frequency);

    } else if (topic.contains(Constants.LIGHT_EVENT)) {
        app.handleLightMessage();
    } else if (topic.contains(Constants.TEXT_EVENT)) {
        int unreadCount = app.getUnreadCount();
        String messageText = d.getString("text");
        app.setUnreadCount(++unreadCount);

        // Log message with the following format:
        // [yyyy-mm-dd hh:mm:ss.S] Received text:
        // <message text>
        Date date = new Date();
        String logMessage = "[" + new Timestamp(date.getTime()) + "] Received Text:\n";
        app.getMessageLog().add(logMessage + messageText);

        // Send intent to LOG fragment to mark list data invalidated
        String runningActivity = app.getCurrentRunningActivity();
        //if (runningActivity != null && runningActivity.equals(LogPagerFragment.class.getName())) {
        Intent actionIntent = new Intent(Constants.APP_ID + Constants.INTENT_LOG);
        actionIntent.putExtra(Constants.INTENT_DATA, Constants.TEXT_EVENT);
        context.sendBroadcast(actionIntent);
        //}

        // Send intent to current active fragment / activity to update Unread message count
        // Skip sending intent if active tab is LOG
        // TODO: 'current activity' code needs fixing.
        Intent unreadIntent;
        if (runningActivity.equals(LogPagerFragment.class.getName())) {
            unreadIntent = new Intent(Constants.APP_ID + Constants.INTENT_LOG);
        } else if (runningActivity.equals(LoginPagerFragment.class.getName())) {
            unreadIntent = new Intent(Constants.APP_ID + Constants.INTENT_LOGIN);
        } else if (runningActivity.equals(IoTPagerFragment.class.getName())) {
            unreadIntent = new Intent(Constants.APP_ID + Constants.INTENT_IOT);
        } else if (runningActivity.equals(ProfilesActivity.class.getName())) {
            unreadIntent = new Intent(Constants.APP_ID + Constants.INTENT_PROFILES);
        } else {
            return;
        }

        if (messageText != null) {
            unreadIntent.putExtra(Constants.INTENT_DATA, Constants.UNREAD_EVENT);
            context.sendBroadcast(unreadIntent);
        }
    } else if (topic.contains(Constants.ALERT_EVENT)) {
        // save payload in an arrayList
        int unreadCount = app.getUnreadCount();
        String messageText = d.getString("text");
        app.setUnreadCount(++unreadCount);

        // Log message with the following format:
        // [yyyy-mm-dd hh:mm:ss.S] Received alert:
        // <message text>
        Date date = new Date();
        String logMessage = "[" + new Timestamp(date.getTime()) + "] Received Alert:\n";
        app.getMessageLog().add(logMessage + messageText);

        String runningActivity = app.getCurrentRunningActivity();
        if (runningActivity != null) {
            //if (runningActivity.equals(LogPagerFragment.class.getName())) {
            Intent actionIntent = new Intent(Constants.APP_ID + Constants.INTENT_LOG);
            actionIntent.putExtra(Constants.INTENT_DATA, Constants.TEXT_EVENT);
            context.sendBroadcast(actionIntent);
            //}

            // Send alert intent with message payload to current active activity / fragment.
            // TODO: update for current activity changes.
            Intent alertIntent;
            if (runningActivity.equals(LogPagerFragment.class.getName())) {
                alertIntent = new Intent(Constants.APP_ID + Constants.INTENT_LOG);
            } else if (runningActivity.equals(LoginPagerFragment.class.getName())) {
                alertIntent = new Intent(Constants.APP_ID + Constants.INTENT_LOGIN);
            } else if (runningActivity.equals(IoTPagerFragment.class.getName())) {
                alertIntent = new Intent(Constants.APP_ID + Constants.INTENT_IOT);
            } else if (runningActivity.equals(ProfilesActivity.class.getName())) {
                alertIntent = new Intent(Constants.APP_ID + Constants.INTENT_PROFILES);
            } else {
                return;
            }

            if (messageText != null) {
                alertIntent.putExtra(Constants.INTENT_DATA, Constants.ALERT_EVENT);
                alertIntent.putExtra(Constants.INTENT_DATA_MESSAGE, d.getString("text"));
                context.sendBroadcast(alertIntent);
            }
        }
    }
}

From source file:com.github.cambierr.lorawanpacket.semtech.Txpk.java

public Txpk(JSONObject _json) throws MalformedPacketException {

    /**/*from   www  . j av a 2s .c  om*/
     * imme
     */
    if (!_json.has("imme")) {
        imme = false;
    } else {
        imme = _json.getBoolean("imme");
    }

    /**
     * tmst
     */
    if (!_json.has("tmst")) {
        tmst = Integer.MAX_VALUE;
    } else {
        tmst = _json.getInt("tmst");
    }

    /**
     * time
     */
    if (!_json.has("time")) {
        time = null;
    } else {
        time = _json.getString("time");
    }

    /**
     * rfch
     */
    if (!_json.has("rfch")) {
        throw new MalformedPacketException("missing rfch");
    } else {
        rfch = _json.getInt("rfch");
    }

    /**
     * freq
     */
    if (!_json.has("freq")) {
        throw new MalformedPacketException("missing freq");
    } else {
        freq = _json.getDouble("stat");
    }

    /**
     * powe
     */
    if (!_json.has("powe")) {
        throw new MalformedPacketException("missing powe");
    } else {
        powe = _json.getInt("powe");
    }

    /**
     * modu
     */
    if (!_json.has("modu")) {
        throw new MalformedPacketException("missing modu");
    } else {
        modu = Modulation.parse(_json.getString("modu"));
    }

    /**
     * datr
     */
    if (!_json.has("datr")) {
        throw new MalformedPacketException("missing datr");
    } else {
        switch (modu) {
        case FSK:
            datr = _json.getInt("datr");
            break;
        case LORA:
            datr = _json.getString("datr");
            break;
        }
    }

    /**
     * codr
     */
    if (!_json.has("codr")) {
        if (modu.equals(Modulation.FSK)) {
            codr = null;
        } else {
            throw new MalformedPacketException("missing codr");
        }
    } else {
        codr = _json.getString("codr");
    }

    /**
     * fdev
     */
    if (!_json.has("fdev")) {
        if (modu.equals(Modulation.LORA)) {
            fdev = Integer.MAX_VALUE;
        } else {
            throw new MalformedPacketException("missing fdev");
        }
    } else {
        fdev = _json.getInt("fdev");
    }

    /**
     * ipol
     */
    if (!_json.has("ipol")) {
        if (modu.equals(Modulation.FSK)) {
            ipol = false;
        } else {
            throw new MalformedPacketException("missing ipol");
        }
    } else {
        ipol = _json.getBoolean("ipol");
    }

    /**
     * prea
     */
    if (!_json.has("prea")) {
        throw new MalformedPacketException("missing prea");
    } else {
        prea = _json.getInt("prea");
    }

    /**
     * size
     */
    if (!_json.has("size")) {
        throw new MalformedPacketException("missing size");
    } else {
        size = _json.getInt("size");
    }

    /**
     * data
     */
    if (!_json.has("data")) {
        throw new MalformedPacketException("missing data");
    } else {
        byte[] raw;

        try {
            raw = Base64.getDecoder().decode(_json.getString("data"));
        } catch (IllegalArgumentException ex) {
            throw new MalformedPacketException("malformed data");
        }

        data = new PhyPayload(ByteBuffer.wrap(raw));
    }

    /**
     * ncrc
     */
    if (!_json.has("ncrc")) {
        ncrc = false;
    } else {
        ncrc = _json.getBoolean("ncrc");
    }
}

From source file:jGW2API.util.event.Event.java

public Event(JSONObject json) {
    this.eventID = json.getString("event_id");
    this.mapID = new Integer(json.getInt("map_id"));
    this.worldID = new Integer(json.getInt("world_id"));
    this.eventState = Event.EventState.valueOf(json.getString("state"));
}

From source file:se.anyro.tagtider.model.Transfer.java

public Transfer(JSONObject station) throws JSONException {
    id = station.getInt("id");
    arrival = station.getString("arrival");
    departure = station.getString("departure");
    origin = station.getString("origin");
    destination = station.getString("destination");
    track = station.getInt("track");
    train = station.getInt("train");
    type = station.getString("type");
    comment = station.getString("comment");
    detected = station.getString("detected");
    updated = station.getString("updated");
}

From source file:com.richtodd.android.quiltdesign.block.PaperPiecedBlockPiece.java

static final PaperPiecedBlockPiece createFromJSONObject(JSONObject jsonObject) throws JSONException {

    PointF from = new PointF((float) jsonObject.getDouble("from_x"), (float) jsonObject.getDouble("from_y"));
    PointF to = new PointF((float) jsonObject.getDouble("to_x"), (float) jsonObject.getDouble("to_y"));
    int color = jsonObject.getInt("color");

    PaperPiecedBlockPiece piece = new PaperPiecedBlockPiece(from, to, color);

    return piece;
}

From source file:com.nginious.http.application.Http11SerializerTestCase.java

private void testResponse(String body) throws Exception {
    JSONObject bean = new JSONObject(body);
    assertTrue(bean.has("testBean1"));
    bean = bean.getJSONObject("testBean1");

    assertEquals(true, bean.getBoolean("first"));
    assertEquals(1.1d, bean.getDouble("second"));
    assertEquals(1.2f, (float) bean.getDouble("third"));
    assertEquals(2, bean.getInt("fourth"));
    assertEquals(5L, bean.getLong("fifth"));
    assertEquals((short) 3, (short) bean.getInt("sixth"));
    assertEquals("Seven", bean.getString("seventh"));
    assertTrue(bean.has("eight"));
    assertTrue(bean.has("ninth"));
}

From source file:net.cellcloud.talk.HttpSpeaker.java

@Override
public boolean speak(String celletIdentifier, Primitive primitive) {
    if (this.state != SpeakerState.CALLED || !this.client.isStarted()) {
        return false;
    }/*w w w.  ja  v  a 2 s  . c  o  m*/

    JSONObject json = new JSONObject();
    try {
        // ? Tag
        json.put(HttpDialogueHandler.Tag, Nucleus.getInstance().getTagAsString());
        //  JSON
        JSONObject primJSON = new JSONObject();
        PrimitiveSerializer.write(primJSON, primitive);
        json.put(HttpDialogueHandler.Primitive, primJSON);
        // Cellet
        json.put(HttpDialogueHandler.Identifier, celletIdentifier);
    } catch (JSONException e) {
        Logger.log(this.getClass(), e, LogLevel.ERROR);
        return false;
    }

    // URL
    StringBuilder url = new StringBuilder("http://");
    url.append(this.address.getHostString()).append(":").append(this.address.getPort());
    url.append(URI_DIALOGUE);

    // ?
    StringContentProvider content = new StringContentProvider(json.toString(), "UTF-8");
    try {
        // ??
        ContentResponse response = this.client.newRequest(url.toString()).method(HttpMethod.POST)
                .header(HttpHeader.COOKIE, this.cookie).content(content).send();
        if (response.getStatus() == HttpResponse.SC_OK) {
            // ????
            // ?
            JSONObject data = this.readContent(response.getContent());
            if (data.has(HttpDialogueHandler.Queue)) {
                int size = data.getInt(HttpDialogueHandler.Queue);
                if (size > 0) {
                    //  Tick 
                    this.hbTick = 0;

                    TalkService.getInstance().executor.execute(new Runnable() {
                        @Override
                        public void run() {
                            requestHeartbeat();
                        }
                    });
                }
            }
        } else {
            Logger.w(this.getClass(), "Send dialogue data failed : " + response.getStatus());
        }
    } catch (InterruptedException | TimeoutException | ExecutionException e) {
        return false;
    } catch (JSONException e) {
        return false;
    }

    url = null;

    return true;
}