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:edu.umass.cs.gigapaxos.paxospackets.AcceptReplyPacket.java

/**
 * @param jsonObject// w  w  w  .j a  v  a 2s . c om
 * @throws JSONException
 */
public AcceptReplyPacket(JSONObject jsonObject) throws JSONException {
    super(jsonObject);
    this.packetType = PaxosPacketType.ACCEPT_REPLY;
    this.acceptor = jsonObject.getInt(PaxosPacket.NodeIDKeys.SNDR.toString());
    this.ballot = new Ballot(jsonObject.getString(PaxosPacket.NodeIDKeys.B.toString()));
    this.slotNumber = jsonObject.getInt(PaxosPacket.Keys.S.toString());
    this.maxCheckpointedSlot = jsonObject.getInt(PaxosPacket.Keys.CP_S.toString());
    this.requestID = jsonObject.getInt(RequestPacket.Keys.QID.toString());
    if (jsonObject.has(PaxosPacket.Keys.NACK.toString()))
        this.undigestRequest = jsonObject.getBoolean(PaxosPacket.Keys.NACK.toString());
}

From source file:com.jeffstephens.castagainsthumanity.GameMessageStream.java

/**
 * Processes all JSON messages received from the receiver device and performs the appropriate 
 * action for the message./*w ww. ja v  a  2s  . c  o m*/
 */
@Override
public void onMessageReceived(JSONObject message) {
    try {
        Log.d(TAG, "onMessageReceived: " + message);
        if (message.has(KEY_TYPE)) {
            String event = message.getString(KEY_TYPE);

            // if we're getting confirmation that we're queued
            if (KEY_USER_QUEUED.equals(event)) {
                Log.d(TAG, "Confirmed enqueued");
                onPlayerQueued();
            }

            // if we're getting confirmation that we've joined
            else if (KEY_USER_JOINED.equals(event)) {
                Log.d(TAG, "Confirmed joined");
                try {
                    int newID = message.getInt(KEY_PLAYER_ID);
                    onPlayerJoined(newID);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            // if the judging period is starting
            else if (KEY_JUDGING_MODE_STARTED.equals(event)) {
                Log.d(TAG, "Judging mode starting");
                onJudgeModeStarted();
            }

            // if we're receiving a game state update (gameSync)
            else if (KEY_GAMESYNC.equals(event)) {
                Log.d(TAG, "GameSync");
                try {
                    JSONObject thisPlayer = message.getJSONObject(KEY_PLAYER_OBJECT);
                    int newJudge = message.getInt(KEY_JUDGE_ID);
                    onGameSync(thisPlayer, newJudge);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            // if we're receiving an array of responses to judge
            else if (KEY_YOU_ARE_JUDGE.equals(event)) {
                Log.d(TAG, "You are judge");
                try {
                    JSONArray responses = message.getJSONArray(KEY_RESPONSES_ARRAY);
                    onJudgeResponses(responses);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            // if we're receiving a new prompt for a new round
            else if (KEY_ROUND_HAS_STARTED.equals(event)) {
                Log.d(TAG, "Round started");
                try {
                    String newPrompt = message.getString(KEY_PROMPT_STRING);
                    int numOfBlanks = message.getInt(KEY_NUM_OF_BLANKS);
                    onRoundStarted(newPrompt, numOfBlanks);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            // if we're receiving notice that a round has ended
            else if (KEY_ROUND_HAS_ENDED.equals(event)) {
                Log.d(TAG, "Round ended");
                onRoundEnded();
            }

            // if we're receiving a response message (possible error)
            else if (KEY_SERVER_RESPONSE.equals(event)) {
                Log.d(TAG, "Response received");
                try {
                    int responseCode = message.getInt(KEY_RESPONSE_CODE);
                    if (responseCode != 0) {
                        onServerError(responseCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        } else {
            Log.w(TAG, "Unknown message (no type): " + message);
        }
    } catch (JSONException e) {
        Log.w(TAG, "Message doesn't contain an expected key.", e);
    }
}

From source file:org.mozilla.gecko.gfx.IntSize.java

public IntSize(JSONObject json) {
    try {/*from  w ww  .j ava2 s  .  com*/
        width = json.getInt("width");
        height = json.getInt("height");
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.dedipower.portal.android.TicketLanding.java

public void onCreate(Bundle savedInstanceState) {
    API.SessionID = getIntent().getStringExtra("sessionid");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ticketlanding);
    final ListView list = (ListView) findViewById(R.id.TicketList);

    final ProgressDialog dialog = ProgressDialog.show(this, "DediPortal", "Please wait: loading data....",
            true);/*from   w  w  w.j a  v a2  s.c om*/
    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            dialog.dismiss();
            if (Success.equals("true")) {
                UpdateErrorMessage(ErrorMessage);
                OpenTicketsAdaptor adapter = new OpenTicketsAdaptor(TicketLanding.this, listOfTickets,
                        API.SessionID);
                list.setAdapter(adapter);
            } else {
                UpdateErrorMessage(ErrorMessage);
            }
        }
    };

    Thread dataPreload = new Thread() {
        public void run() {
            try {
                TicketAPI = API.PortalQuery("tickets", "none");
                Success = TicketAPI.getString("success");
            } catch (JSONException e) {
                ErrorMessage = "An unrecoverable JSON Exception occured.";
                Success = "false";
            }

            if (Success.equals("false")) {
                try {
                    ErrorMessage = TicketAPI.getString("msg");
                } catch (JSONException e) {
                    ErrorMessage = "A JSON parsing error prevented an exact error message to be determined.";
                }
            } else {
                Log.i("APIFuncs", TicketAPI.toString());
                try {
                    Tickets = TicketAPI.getJSONArray("tickets");
                    ErrorMessage = "";
                } catch (JSONException e) {
                    ErrorMessage = "There are no open tickets for your account.";
                }

                //OK lets actually do something useful
                //ListView list = (ListView)findViewById(R.id.TicketList);
                //List<OpenTickets> listOfTickets = new ArrayList<OpenTickets>();
                int TicketCount = Tickets.length();

                if (TicketCount == 0) {
                    ErrorMessage = "There are no open tickets for your account.";
                    handler.sendEmptyMessage(0);
                    return;
                }

                for (int i = 0; i < TicketCount; i++) {
                    JSONObject CurrentTicket = null;
                    try {
                        CurrentTicket = Tickets.getJSONObject(i);
                    } catch (JSONException e1) {
                        Log.e("APIFuncs", e1.getMessage());
                    }
                    try {
                        listOfTickets.add(new OpenTickets(CurrentTicket.getString("status"),
                                CurrentTicket.getInt("id"), CurrentTicket.getString("server"),
                                CurrentTicket.getString("email"), CurrentTicket.getString("subject"),
                                CurrentTicket.getInt("createdat"), CurrentTicket.getInt("lastupdate"), false));
                        //CurrentTicket.getBoolean("subscriber")));
                    } catch (JSONException e) {
                        Log.e("APIFuncs", e.getMessage());
                    }
                }
            }

            handler.sendEmptyMessage(0);
        }
    };

    dataPreload.start();
}

From source file:com.wholegroup.rally.Rally.java

/**
 * ??   JSON ?./*from  w w  w  .  j  av a 2  s. c  om*/
 */
public void fromJSON(String strJSON) {
    try {
        JSONObject jsonObject = new JSONObject(strJSON);
        JSONArray jsonArray;
        JSONArray jsonArray2;

        jsonArray = jsonObject.getJSONArray("m_arrField");

        for (int y = 0; y < jsonArray.length(); y++) {
            if (FIELDHEIGHT <= y) {
                break;
            }

            jsonArray2 = jsonArray.getJSONArray(y);

            for (int x = 0; x < jsonArray2.length(); x++) {
                if (FIELDWIDTH <= x) {
                    break;
                }

                m_arrField[y][x] = jsonArray2.getInt(x);
            }
        }

        m_iScore = jsonObject.getInt("m_iScore");
        m_iTypeGame = jsonObject.getInt("m_iTypeGame");
        m_iPlayerPos = jsonObject.getInt("m_iPlayerPos");
        m_iLifeCount = jsonObject.getInt("m_iLifeCount");
        m_iDensity = jsonObject.getInt("m_iDensity");
        m_iSpeedMS = jsonObject.getInt("m_iSpeedMS");
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:org.archive.modules.writer.WriterPoolProcessor.java

@Override
protected void fromCheckpointJson(JSONObject json) throws JSONException {
    super.fromCheckpointJson(json);
    serial.set(json.getInt("serialNumber"));
}

From source file:com.github.koraktor.steamcondenser.community.GameItem.java

/**
 * Creates a new instance of a GameItem with the given data
 *
 * @param inventory The inventory this item is contained in
 * @param itemData The data specifying this item
 * @throws WebApiException on Web API errors
 *//*from  w  w w . j  a v  a2s . c  o  m*/
public GameItem(GameInventory inventory, JSONObject itemData) throws SteamCondenserException {
    this.inventory = inventory;

    try {
        this.defindex = itemData.getInt("defindex");
        this.backpackPosition = (int) itemData.getLong("inventory") & 0xffff;
        this.count = itemData.getInt("quantity");
        this.craftable = !itemData.optBoolean("flag_cannot_craft");
        this.id = itemData.getInt("id");
        this.itemClass = this.getSchemaData().getString("item_class");
        this.itemSet = this.inventory.getItemSchema().getItemSets()
                .get(this.getSchemaData().optString("item_set"));
        this.level = itemData.getInt("level");
        this.name = this.getSchemaData().getString("item_name");
        this.preliminary = (itemData.getLong("inventory") & 0x40000000) != 0;
        this.originalId = itemData.getInt("original_id");
        this.quality = this.inventory.getItemSchema().getQualities().get(itemData.getInt("quality"));
        this.tradeable = !itemData.optBoolean("flag_cannot_trade");
        this.type = this.getSchemaData().getString("item_type_name");

        if (itemData.has("origin")) {
            this.origin = this.inventory.getItemSchema().getOrigins().get(itemData.getInt("origin"));
        }

        JSONArray attributesData = this.getSchemaData().optJSONArray("attributes");
        if (attributesData == null) {
            attributesData = new JSONArray();
        }
        if (itemData.has("attributes")) {
            JSONArray itemAttributes = itemData.getJSONArray("attributes");
            for (int i = 0; i < itemAttributes.length(); i++) {
                attributesData.put(itemAttributes.get(i));
            }
        }

        this.attributes = new ArrayList<JSONObject>();
        for (int i = 0; i < attributesData.length(); i++) {
            JSONObject attributeData = attributesData.getJSONObject(i);
            Object attributeKey = attributeData.opt("defindex");
            if (attributeKey == null) {
                attributeKey = attributeData.opt("name");
            }

            if (attributeKey != null) {
                JSONObject schemaAttributeData = inventory.getItemSchema().getAttributes().get(attributeKey);
                for (String key : JSONObject.getNames(schemaAttributeData)) {
                    attributeData.put(key, schemaAttributeData.get(key));
                }
                this.attributes.add(attributeData);
            }
        }
    } catch (JSONException e) {
        throw new WebApiException("Could not parse JSON data.", e);
    }
}

From source file:cn.ttyhuo.view.UserView.java

public void setupViews(JSONObject jsonObject, final Context context) throws JSONException {

    JSONObject jObject;
    if (jsonObject.has("user"))
        jObject = jsonObject.getJSONObject("user");
    else/* www  .j  a va2  s  . c o  m*/
        jObject = jsonObject.getJSONObject("userWithLatLng");

    String userStatus = JSONUtil.getStringFromJson(jObject, "status", "");
    if (!userStatus.equals("")) {
        if (tv_userStatus != null)
            tv_userStatus.setText("(" + userStatus + ")");
    } else {
        if (tv_userStatus != null)
            tv_userStatus.setText("");
    }

    if (tv_userTypeStr != null)
        tv_userTypeStr.setText(JSONUtil.getStringFromJson(jsonObject, "userTypeStr", ""));

    String userName = JSONUtil.getStringFromJson(jObject, "userName", "??");
    String imgUrl = JSONUtil.getStringFromJson(jObject, "imgUrl", "");
    int verifyFlag = 0;
    if (JSONUtil.getBoolFromJson(jObject, "sfzVerify")) {
        verifyFlag = 1;
        iv_userVerify.setVisibility(View.VISIBLE);
        imgUrl = JSONUtil.getStringFromJson(jObject, "faceImgUrl", imgUrl);
        userName = JSONUtil.getStringFromJson(jObject, "identityName", userName);
    } else {
        iv_userVerify.setVisibility(View.GONE);
    }
    tv_userName.setText(userName);

    int gender = JSONUtil.getIntFromJson(jsonObject, "gender", 0);
    if (gender == 2) {
        iv_gender.setImageResource(R.drawable.icon_nv_big);
        ll_gender.setBackgroundResource(R.drawable.bg_nv);
    } else if (gender == 1) {
        iv_gender.setImageResource(R.drawable.icon_nan_big);
        ll_gender.setBackgroundResource(R.drawable.bg_nan);
    } else {
        //TODO:??
    }

    Integer age = JSONUtil.getIntFromJson(jsonObject, "age", 0);
    tv_userAge.setText(age.toString());

    double lat = JSONUtil.getDoubleFromJson(jObject, "lat", 0.0);
    double lng = JSONUtil.getDoubleFromJson(jObject, "lng", 0.0);

    String distance = ((MyApplication) ((Activity) context).getApplication()).getDistance(lat, lng);

    //TODO:
    tv_lastPlace.setText(distance + "km");
    JSONUtil.setValueFromJson(tv_lastTime, jObject, "latlngDate", "");
    if (tv_mobileNo != null) {
        String mobileNo = JSONUtil.getStringFromJson(jObject, "mobileNo", "");
        if (mobileNo.length() > 7) {
            mobileNo = mobileNo.substring(0, 3) + "****" + mobileNo.substring(7);
        }
        tv_mobileNo.setText(mobileNo);
    }

    int thumbUpCount = jObject.getInt("thumbUpCount");
    int favoriteUserCount = jObject.getInt("favoriteUserCount");
    boolean alreadyFavorite = jObject.getBoolean("alreadyFavorite");
    final int userID = jObject.getInt("userID");

    setFavoriteAndThumbUp(userID, thumbUpCount, favoriteUserCount, alreadyFavorite, context, jObject);

    if (JSONUtil.getBoolFromJson(jsonObject, "hasProduct")) {
        iv_hasProduct.setVisibility(View.GONE);
        tv_hasProduct.setVisibility(View.VISIBLE);

        View.OnClickListener theClick = new View.OnClickListener() {
            //  ? ?
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                case R.id.iv_hasProduct:
                case R.id.tv_hasProduct:
                    Intent intent = new Intent(context, MainPage.class);
                    intent.putExtra("contentFragment", "UserProductFragment");
                    intent.putExtra("windowTitle", "?");
                    intent.putExtra("hasWindowTitle", true);
                    intent.putExtra("extraID", userID);
                    context.startActivity(intent);
                    break;

                default:
                    break;
                }
            }
        };
        iv_hasProduct.setOnClickListener(theClick);
        tv_hasProduct.setOnClickListener(theClick);
    } else {
        iv_hasProduct.setVisibility(View.GONE);
        tv_hasProduct.setVisibility(View.GONE);
    }

    verifyFlag = setupTruckInfo(context, jObject, jsonObject, verifyFlag);

    if (fl_title != null) {
        JSONUtil.setFieldValueFromJson(fl_title, jsonObject, "title", "");
        JSONUtil.setFieldValueFromJson(fl_description, jsonObject, "description", "");
        JSONUtil.setFieldValueFromJson(fl_hobby, jsonObject, "hobby", "");
        JSONUtil.setFieldValueFromJson(fl_homeTown, jsonObject, "homeTown", "");
        JSONUtil.setFieldValueFromJson(fl_createDate, jObject, "createDate", "");
    }

    verifyFlag = setupCompanyInfo(jsonObject, jObject, verifyFlag);

    setupUserVerifyImg(jObject, verifyFlag);

    setupFaceImg(context, imgUrl);

    if (iv_qrcode != null) {
        Map<String, String> params = new HashMap<String, String>();
        StringBuilder buf = new StringBuilder("http://qr.liantu.com/api.php");
        params.put("text", "http://ttyh.aliapp.com/mvc/viewUser_" + userID);
        params.put("bg", "ffffff");
        params.put("fg", "cc0000");
        params.put("fg", "gc0000");
        params.put("el", "h");
        params.put("w", "300");
        params.put("m", "10");
        params.put("pt", "00ff00");
        params.put("inpt", "000000");
        params.put("logo", "http://ttyh-document.oss-cn-qingdao.aliyuncs.com/ic_launcher.jpg");
        try {
            // GET?URL
            if (params != null && !params.isEmpty()) {
                buf.append("?");
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    buf.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "UTF-8"))
                            .append("&");
                }
                buf.deleteCharAt(buf.length() - 1);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        final String qrcodeUrl = buf.toString();
        ImageLoader.getInstance().displayImage(qrcodeUrl, iv_qrcode, new DisplayImageOptions.Builder()
                .resetViewBeforeLoading(true).cacheInMemory(true).cacheOnDisc(true).build());

        iv_qrcode.setOnClickListener(new View.OnClickListener() {
            //  ? ?
            @Override
            public void onClick(View v) {
                try {
                    FileOutputStream fos = context.openFileOutput("qrcode.png", Context.MODE_WORLD_READABLE);
                    FileInputStream fis = new FileInputStream(
                            ImageLoader.getInstance().getDiscCache().get(qrcodeUrl));
                    byte[] buf = new byte[1024];
                    int len = 0;
                    while ((len = fis.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    fis.close();
                    fos.close();
                    shareMsg(context, "?", "?",
                            "??: ",
                            context.getFileStreamPath("qrcode.png"));
                } catch (Exception e) {
                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                }
            }
        });
    }

    final String mobile = JSONUtil.getStringFromJson(jObject, "mobileNo", "");
    if (!mobile.isEmpty()) {
        if (tv_footer_call_btn != null) {
            tv_footer_call_btn.setOnClickListener(new View.OnClickListener() {
                //  ? ?
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.CALL");
                    intent.setData(Uri.parse("tel:" + mobile));//mobile??????
                    context.startActivity(intent);
                }
            });
        }

        if (iv_phoneIcon != null) {
            iv_phoneIcon.setOnClickListener(new View.OnClickListener() {
                //  ? ?
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.CALL");
                    intent.setData(Uri.parse("tel:" + mobile));//mobile??????
                    context.startActivity(intent);
                }
            });
        }
    } else {
        if (tv_footer_call_btn != null)
            tv_footer_call_btn.setOnClickListener(null);
        if (iv_phoneIcon != null)
            iv_phoneIcon.setOnClickListener(null);
    }
}

From source file:tech.salroid.filmy.tmdb_account.AddRating.java

private void parseMarkedResponse(JSONObject response) {

    try {//ww  w  .  ja  va2s . c o  m
        int status_code = response.getInt("status_code");

        if (status_code == 1) {

            CustomToast.show(context, "Your rating has been added.", false);

            mBuilder.setContentText("Movie rating done.")
                    // Removes the progress bar
                    .setProgress(0, 0, false);
            mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
            mNotifyManager.cancel(NOTIFICATION_ID);

        } else if (status_code == 12) {

            CustomToast.show(context, "Rating updated.", false);

            mBuilder.setContentText("Rating updated.")
                    // Removes the progress bar
                    .setProgress(0, 0, false);
            mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
            mNotifyManager.cancel(NOTIFICATION_ID);
        }

    } catch (JSONException e) {
        Log.d("webi", e.getCause().toString());

        mBuilder.setContentText("Can't add rating.")
                // Removes the progress bar
                .setProgress(0, 0, false);
        mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
        mNotifyManager.cancel(NOTIFICATION_ID);

        CustomToast.show(context, "Can't add rating.", false);
    }

}

From source file:jessmchung.groupon.parsers.DealOptionsParser.java

@Override
public DealOptions parse(JSONObject json) throws JSONException {
    DealOptions obj = new DealOptions();
    if (json.has("buyUrl"))
        obj.setBuyUrl(json.getString("buyUrl"));
    if (json.has("expiresAt")) {
        try {// ww w. j a  v  a 2  s .  co m
            obj.setExpiresAt(parseDate(json.getString("expiresAt")));
        } catch (ParseException ex) {
            System.out.println("Could not parse " + json.getString("expiresAt"));
        }
    }
    if (json.has("price")) {
        JSONObject price = json.getJSONObject("price");
        obj.setPrice(new PriceParser().parse(price));
    }
    if (json.has("discountPercent"))
        obj.setDiscountPercent(json.getDouble("discountPercent"));
    if (json.has("soldQuantity"))
        obj.setSoldQuantity(json.getInt("soldQuantity"));
    if (json.has("initialQuantity") && !json.isNull("initialQuantity"))
        obj.setInitialQuantity(json.getInt("initialQuantity"));
    if (json.has("externalUrl"))
        obj.setExternalUrl(json.getString("externalUrl"));
    if (json.has("minimumPurchaseQuantity"))
        obj.setMinimumPurchaseQuantity(json.getInt("minimumPurchaseQuantity"));
    if (json.has("limitedQuantity"))
        obj.setIsLimitedQuantity(json.getBoolean("isLimitedQuantity"));
    if (json.has("value")) {
        JSONObject value = json.getJSONObject("value");
        obj.setValue(new PriceParser().parse(value));
    }
    if (json.has("maximumPurchaseQuantity"))
        obj.setMaximumPurchaseQuantity(json.getInt("maximumPurchaseQuantity"));
    if (json.has("title"))
        obj.setTitle(json.getString("title"));
    if (json.has("discount")) {
        JSONObject discount = json.getJSONObject("discount");
        obj.setValue(new PriceParser().parse(discount));
    }
    if (json.has("remainingQuantity") && !json.isNull("remainingQuantity"))
        obj.setRemainingQuantity(json.getInt("remainingQuantity"));
    if (json.has("id"))
        obj.setId(json.getInt("id"));
    if (json.has("isSoldOut"))
        obj.setIsSoldOut(json.getBoolean("isSoldOut"));
    if (json.has("redemptionLocations")) {
        JSONArray locationsArray = json.getJSONArray("redemptionLocations");
        obj.setRedemptionLocations(new RedemptionLocationParser().parse(locationsArray));
    }

    return obj;
}