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.ibm.hellotodoadvanced.MainActivity.java

/**
 * Uses Bluemix Mobile Services SDK to GET the TodoItems from Bluemix and updates the local list.
 *//*from w w  w  . j  av  a  2  s.  c  o m*/
private void loadList() {

    // Send GET Request to Bluemix backend to retreive item list with response listener
    Request request = new Request(bmsClient.getBluemixAppRoute() + "/api/Items", Request.GET);
    request.send(getApplicationContext(), new ResponseListener() {
        // Loop through JSON response and create local TodoItems if successful
        @Override
        public void onSuccess(Response response) {
            if (response.getStatus() != 200) {
                Log.e(TAG, "Error pulling items from Bluemix: " + response.toString());
            } else {

                try {

                    mTodoItemList.clear();

                    JSONArray jsonArray = new JSONArray(response.getResponseText());

                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject tempTodoJSON = jsonArray.getJSONObject(i);
                        TodoItem tempTodo = new TodoItem();

                        tempTodo.idNumber = tempTodoJSON.getInt("id");
                        tempTodo.text = tempTodoJSON.getString("text");
                        tempTodo.isDone = tempTodoJSON.getBoolean("isDone");

                        mTodoItemList.add(tempTodo);
                    }

                    // Need to notify adapter on main thread in order for list changes to update visually
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mTodoItemAdapter.notifyDataSetChanged();

                            Log.i(TAG, "List updated successfully");

                            if (mSwipeLayout.isRefreshing()) {
                                mSwipeLayout.setRefreshing(false);
                            }
                        }
                    });

                } catch (Exception exception) {
                    Log.e(TAG, "Error reading response JSON: " + exception.getLocalizedMessage());
                }
            }
        }

        // Log Errors on failure
        @Override
        public void onFailure(Response response, Throwable throwable, JSONObject extendedInfo) {
            String errorMessage = "";

            if (response != null) {
                errorMessage += response.toString() + "\n";
            }

            if (throwable != null) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                throwable.printStackTrace(pw);
                errorMessage += "THROWN" + sw.toString() + "\n";
            }

            if (extendedInfo != null) {
                errorMessage += "EXTENDED_INFO" + extendedInfo.toString() + "\n";
            }

            if (errorMessage.isEmpty())
                errorMessage = "Request Failed With Unknown Error.";

            Log.e(TAG, "loadList failed with error: " + errorMessage);
        }
    });

}

From source file:com.habzy.syncontacts.platform.User.java

/**
 * Creates and returns an instance of the user from the provided JSON data.
 * /*from   w  w w  .  j a va 2s  . co m*/
 * @param user The JSONObject containing user data
 * @return user The new instance of Voiper user created from the JSON data.
 */
public static User valueOf(JSONObject user) {
    try {
        final String userName = user.getString("u");
        final String firstName = user.has("f") ? user.getString("f") : null;
        final String lastName = user.has("l") ? user.getString("l") : null;
        final String cellPhone = user.has("m") ? user.getString("m") : null;
        final String officePhone = user.has("o") ? user.getString("o") : null;
        final String homePhone = user.has("h") ? user.getString("h") : null;
        final String email = user.has("e") ? user.getString("e") : null;
        final boolean deleted = user.has("d") ? user.getBoolean("d") : false;
        final int userId = user.getInt("i");
        return new User(userName, firstName, lastName, cellPhone, officePhone, homePhone, email, deleted,
                userId);
    } catch (final Exception ex) {
        Log.i("User", "Error parsing JSON user object" + ex.toString());

    }
    return null;

}

From source file:org.dasein.cloud.aws.compute.EC2Instance.java

private @Nullable VirtualMachineProduct toProduct(@Nonnull JSONObject json) throws InternalException {
    /*//from  w ww . ja v  a  2  s. co m
            {
        "architectures":["I32"],
        "id":"m1.small",
        "name":"Small Instance (m1.small)",
        "description":"Small Instance (m1.small)",
        "cpuCount":1,
        "rootVolumeSizeInGb":160,
        "ramSizeInMb": 1700
    },
     */
    VirtualMachineProduct prd = new VirtualMachineProduct();

    try {
        if (json.has("id")) {
            prd.setProviderProductId(json.getString("id"));
        } else {
            return null;
        }
        if (json.has("name")) {
            prd.setName(json.getString("name"));
        } else {
            prd.setName(prd.getProviderProductId());
        }
        if (json.has("description")) {
            prd.setDescription(json.getString("description"));
        } else {
            prd.setDescription(prd.getName());
        }
        if (json.has("cpuCount")) {
            prd.setCpuCount(json.getInt("cpuCount"));
        } else {
            prd.setCpuCount(1);
        }
        if (json.has("rootVolumeSizeInGb")) {
            prd.setRootVolumeSize(new Storage<Gigabyte>(json.getInt("rootVolumeSizeInGb"), Storage.GIGABYTE));
        } else {
            prd.setRootVolumeSize(new Storage<Gigabyte>(1, Storage.GIGABYTE));
        }
        if (json.has("ramSizeInMb")) {
            prd.setRamSize(new Storage<Megabyte>(json.getInt("ramSizeInMb"), Storage.MEGABYTE));
        } else {
            prd.setRamSize(new Storage<Megabyte>(512, Storage.MEGABYTE));
        }
        if (json.has("generation") && json.getString("generation").equalsIgnoreCase("previous")) {
            prd.setStatusDeprecated();
        }
        if (json.has("standardHourlyRates")) {
            JSONArray rates = json.getJSONArray("standardHourlyRates");

            for (int i = 0; i < rates.length(); i++) {
                JSONObject rate = rates.getJSONObject(i);

                if (rate.has("rate")) {
                    prd.setStandardHourlyRate((float) rate.getDouble("rate"));
                }
            }
        }
    } catch (JSONException e) {
        throw new InternalException(e);
    }
    return prd;
}

From source file:com.asd.littleprincesbeauty.data.TaskList.java

@Override
public void setContentByLocalJSON(JSONObject js) {
    if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
        Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
    }/*  w  w  w .  j  ava  2 s. com*/

    try {
        JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);

        if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
            String name = folder.getString(NoteColumns.SNIPPET);
            setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);
        } else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
            if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER)
                setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);
            else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER)
                setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE);
            else
                Log.e(TAG, "invalid system folder");
        } else {
            Log.e(TAG, "error type");
        }
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
    }
}

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

private void handleSearchResults(JSONObject json) {
    try {// w  ww .  java 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;

    }

}

From source file:com.md87.charliebravo.commands.DefineCommand.java

public void execute(final InputHandler handler, Response response, String line)
        throws MalformedURLException, IOException, JSONException {
    URL url = new URL("http://apps.md87.co.uk/services/wiktionary/?query="
            + URLEncoder.encode(line, Charset.defaultCharset().name()));
    URLConnection connection = url.openConnection();
    connection.addRequestProperty("Referer", "http://chris.smith.name/");

    String input;/*  w  w  w  . ja v  a  2 s . c o m*/
    StringBuilder builder = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    while ((input = reader.readLine()) != null) {
        builder.append(input);
    }

    JSONObject json = new JSONObject(builder.toString());
    if (json.getInt("responseStatus") != 200) {
        throw new IOException(json.getString("responseDetails"));
    }

    if (json.getJSONArray("responseData").length() == 0) {
        response.sendMessage("There were no results for '" + line + "'", true);
    } else {
        final StringBuilder res = new StringBuilder();
        res.append("there ");

        if (json.getJSONArray("responseData").length() == 1) {
            res.append("was 1 match");
        } else {
            res.append("were ");
            res.append(json.getJSONArray("responseData").length());
            res.append(" matches");
        }

        res.append(" for '");
        res.append(line);
        res.append("'");

        if (json.getJSONArray("responseData").length() == 1) {
            res.append(". It is ");
        } else {
            res.append(". Result 1 is ");
        }

        final String name = json.getJSONArray("responseData").getJSONObject(0).getString("title");

        res.append('\'');
        res.append(name);
        res.append("', which has ");

        final int defs = json.getJSONArray("responseData").getJSONObject(0).getJSONArray("definitions")
                .length();
        res.append(defs);

        res.append(" definition");

        if (defs != 1) {
            res.append("s, the first of which is");
        }

        res.append(": ");

        res.append(json.getJSONArray("responseData").getJSONObject(0).getJSONArray("definitions").get(0));

        response.sendMessage(res.toString());
        response.addFollowup(new NextWordFollowup(json.getJSONArray("responseData"), 1));
        response.addFollowup(new NextDefinitionFollowup(
                json.getJSONArray("responseData").getJSONObject(0).getJSONArray("definitions"), 1,
                new NextWordFollowup(json.getJSONArray("responseData"), 1)));
    }
}

From source file:fr.cobaltians.cobalt.fragments.CobaltFragment.java

private boolean handleUi(String control, JSONObject data, String callback) {
    try {/*from   ww  w . j a  v a  2 s .c  om*/
        // PICKER
        switch (control) {
        case Cobalt.JSControlPicker:
            String type = data.getString(Cobalt.kJSType);

            // DATE
            if (type.equals(Cobalt.JSPickerDate)) {
                JSONObject date = data.optJSONObject(Cobalt.kJSDate);

                Calendar calendar = Calendar.getInstance();
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH);
                int day = calendar.get(Calendar.DAY_OF_MONTH);

                if (date != null && date.has(Cobalt.kJSYear) && date.has(Cobalt.kJSMonth)
                        && date.has(Cobalt.kJSDay)) {
                    year = date.getInt(Cobalt.kJSYear);
                    month = date.getInt(Cobalt.kJSMonth) - 1;
                    day = date.getInt(Cobalt.kJSDay);
                }

                JSONObject texts = data.optJSONObject(Cobalt.kJSTexts);
                String title = texts.optString(Cobalt.kJSTitle, null);
                //String delete = texts.optString(Cobalt.kJSDelete, null);
                String clear = texts.optString(Cobalt.kJSClear, null);
                String cancel = texts.optString(Cobalt.kJSCancel, null);
                String validate = texts.optString(Cobalt.kJSValidate, null);

                showDatePickerDialog(year, month, day, title, clear, cancel, validate, callback);

                return true;
            }

            break;
        case Cobalt.JSControlAlert:
            showAlertDialog(data, callback);
            return true;
        case Cobalt.JSControlToast:
            String message = data.getString(Cobalt.kJSMessage);
            Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
            return true;
        default:
            break;
        }
    } catch (JSONException exception) {
        if (Cobalt.DEBUG)
            Log.e(Cobalt.TAG, TAG + " - handleUi: JSONException");
        exception.printStackTrace();
    }

    // UNHANDLED UI
    try {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put(Cobalt.kJSType, Cobalt.JSTypeUI);
        jsonObj.put(Cobalt.kJSUIControl, control);
        jsonObj.put(Cobalt.kJSData, data);
        jsonObj.put(Cobalt.kJSCallback, callback);
        onUnhandledMessage(jsonObj);
    } catch (JSONException exception) {
        if (Cobalt.DEBUG)
            Log.e(Cobalt.TAG, TAG + " - handleUi: JSONException");
        exception.printStackTrace();
    }

    return false;
}

From source file:com.hackathon.gavin.string.parser.MyAccountParser.java

public static ArrayList convertToArrayList(JSONArray orginalData) {
    ArrayList<String> allElements = new ArrayList<String>();
    for (int i = 0; i < orginalData.length(); i++) {
        try {/*  w w  w.  ja  v  a 2 s .  co  m*/
            JSONObject obj = orginalData.getJSONObject(i);
            allElements.add(Integer.toString(obj.getInt("id")));
            allElements.add(Integer.toString(obj.getInt("units")));
            allElements.add(obj.getString("instrument"));
            allElements.add(String.valueOf(obj.getDouble("price")));
            System.out.println(allElements);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return allElements;
}

From source file:org.openhab.habdroid.model.OpenHABWidget.java

public OpenHABWidget(OpenHABWidget parent, JSONObject widgetJson) {
    this.parent = parent;
    this.children = new ArrayList<OpenHABWidget>();
    this.mappings = new ArrayList<OpenHABWidgetMapping>();
    try {/*from  w w w  .  j ava  2s. c o m*/
        if (widgetJson.has("item")) {
            this.setItem(new OpenHABItem(widgetJson.getJSONObject("item")));
        }
        if (widgetJson.has("linkedPage")) {
            this.setLinkedPage(new OpenHABLinkedPage(widgetJson.getJSONObject("linkedPage")));
        }
        if (widgetJson.has("mappings")) {
            JSONArray mappingsJsonArray = widgetJson.getJSONArray("mappings");
            for (int i = 0; i < mappingsJsonArray.length(); i++) {
                JSONObject mappingObject = mappingsJsonArray.getJSONObject(i);
                OpenHABWidgetMapping mapping = new OpenHABWidgetMapping(mappingObject.getString("command"),
                        mappingObject.getString("label"));
                mappings.add(mapping);
            }
        }
        if (widgetJson.has("type"))
            this.setType(widgetJson.getString("type"));
        if (widgetJson.has("widgetId"))
            this.setId(widgetJson.getString("widgetId"));
        if (widgetJson.has("label"))
            this.setLabel(widgetJson.getString("label"));
        if (widgetJson.has("icon"))
            this.setIcon(widgetJson.getString("icon"));
        if (widgetJson.has("url"))
            this.setUrl(widgetJson.getString("url"));
        if (widgetJson.has("minValue"))
            this.setMinValue((float) widgetJson.getDouble("minValue"));
        if (widgetJson.has("maxValue"))
            this.setMaxValue((float) widgetJson.getDouble("maxValue"));
        if (widgetJson.has("step"))
            this.setStep((float) widgetJson.getDouble("step"));
        if (widgetJson.has("refresh"))
            this.setRefresh(widgetJson.getInt("refresh"));
        if (widgetJson.has("period"))
            this.setPeriod(widgetJson.getString("period"));
        if (widgetJson.has("service"))
            this.setService(widgetJson.getString("service"));
        if (widgetJson.has("height"))
            this.setHeight(widgetJson.getInt("height"));
        if (widgetJson.has("iconcolor"))
            this.setIconColor(widgetJson.getString("iconcolor"));
        if (widgetJson.has("labelcolor"))
            this.setLabelColor(widgetJson.getString("labelcolor"));
        if (widgetJson.has("valuecolor"))
            this.setValueColor(widgetJson.getString("valuecolor"));
        if (widgetJson.has("encoding"))
            this.setEncoding(widgetJson.getString("encoding"));
    } catch (JSONException e) {
        e.printStackTrace();
    }
    if (widgetJson.has("widgets")) {
        try {
            JSONArray childWidgetJsonArray = widgetJson.getJSONArray("widgets");
            for (int i = 0; i < childWidgetJsonArray.length(); i++) {
                new OpenHABWidget(this, childWidgetJsonArray.getJSONObject(i));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    this.parent.addChildWidget(this);
}

From source file:com.neuron.trafikanten.dataProviders.trafikanten.TrafikantenRealtime.java

@Override
public void run() {
    try {/*ww  w. jav a2s  .c om*/
        final String urlString = Trafikanten.getApiUrl() + "/reisrest/realtime/GetAllDepartures/" + stationId;
        Log.i(TAG, "Loading realtime data : " + urlString);

        final StreamWithTime streamWithTime = HelperFunctions.executeHttpRequest(context,
                new HttpGet(urlString), true);
        ThreadHandleTimeData(streamWithTime.timeDifference);

        /*
         * Parse json
         */
        //long perfSTART = System.currentTimeMillis();
        //Log.i(TAG,"PERF : Getting realtime data");
        final JSONArray jsonArray = new JSONArray(HelperFunctions.InputStreamToString(streamWithTime.stream));
        final int arraySize = jsonArray.length();
        for (int i = 0; i < arraySize; i++) {
            final JSONObject json = jsonArray.getJSONObject(i);
            RealtimeData realtimeData = new RealtimeData();
            try {
                realtimeData.expectedDeparture = HelperFunctions
                        .jsonToDate(json.getString("ExpectedDepartureTime"));
            } catch (org.json.JSONException e) {
                realtimeData.expectedDeparture = HelperFunctions
                        .jsonToDate(json.getString("ExpectedArrivalTime"));
            }

            try {
                realtimeData.lineId = json.getInt("LineRef");
            } catch (org.json.JSONException e) {
                realtimeData.lineId = -1;
            }

            try {
                realtimeData.vehicleMode = json.getInt("VehicleMode");
            } catch (org.json.JSONException e) {
                realtimeData.vehicleMode = 0; // default = bus
            }

            try {
                realtimeData.destination = json.getString("DestinationName");
            } catch (org.json.JSONException e) {
                realtimeData.destination = "Ukjent";
            }

            try {
                realtimeData.departurePlatform = json.getString("DeparturePlatformName");
                if (realtimeData.departurePlatform.equals("null")) {
                    realtimeData.departurePlatform = "";
                }

            } catch (org.json.JSONException e) {
                realtimeData.departurePlatform = "";
            }

            try {
                realtimeData.realtime = json.getBoolean("Monitored");
            } catch (org.json.JSONException e) {
                realtimeData.realtime = false;
            }
            try {
                realtimeData.lineName = json.getString("PublishedLineName");
            } catch (org.json.JSONException e) {
                realtimeData.lineName = "";
            }

            try {
                if (json.has("InCongestion")) {
                    realtimeData.inCongestion = json.getBoolean("InCongestion");
                }
            } catch (org.json.JSONException e) {
                // can happen when incongestion is empty string.
            }

            try {
                if (json.has("VehicleFeatureRef")) {
                    realtimeData.lowFloor = json.getString("VehicleFeatureRef").equals("lowFloor");
                }
            } catch (org.json.JSONException e) {
                // lowfloor = false by default
            }

            try {
                if (json.has("TrainBlockPart") && !json.isNull("TrainBlockPart")) {
                    JSONObject trainBlockPart = json.getJSONObject("TrainBlockPart");
                    if (trainBlockPart.has("NumberOfBlockParts")) {
                        realtimeData.numberOfBlockParts = trainBlockPart.getInt("NumberOfBlockParts");
                    }
                }
            } catch (org.json.JSONException e) {
                // trainblockpart is initialized by default
            }

            ThreadHandlePostData(realtimeData);
        }

        //Log.i(TAG,"PERF : Parsing web request took " + ((System.currentTimeMillis() - perfSTART)) + "ms");

    } catch (Exception e) {
        if (e.getClass() == InterruptedException.class) {
            ThreadHandlePostExecute(null);
            return;
        }
        ThreadHandlePostExecute(e);
        return;
    }
    ThreadHandlePostExecute(null);
}