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:at.alladin.rmbt.android.views.ResultGraphView.java

/**
 * /*from w w  w.j  a v  a2 s .co m*/
 * @param graphArray
 * @param graphView
 * @throws JSONException
 */
public void drawCurve(JSONArray graphArray, CustomizableGraphView graphView, String color, String labelHMax)
        throws JSONException {
    final double maxTime = graphArray.optJSONObject(graphArray.length() - 1).optDouble("time_elapsed");
    //final double pointDistance = (0.25d / (maxTime / 1000));

    graphView.getLabelHMaxList().clear();
    graphView.addLabelHMax(labelHMax);

    //StaticGraph signal = StaticGraph.addGraph(graphView, Color.parseColor(color));
    GraphService signal = SmoothGraph.addGraph(graphView, Color.parseColor(color),
            RMBTTestFragment.SMOOTHING_DATA_AMOUNT, RMBTTestFragment.SMOOTHING_FUNCTION, false);

    if (graphArray != null && graphArray.length() > 0) {
        long bytes = 0;
        for (int i = 0; i < graphArray.length(); i++) {
            JSONObject uploadObject = graphArray.getJSONObject(i);
            double time_elapsed = uploadObject.getInt("time_elapsed");
            bytes = uploadObject.getInt("bytes_total");
            double bitPerSec = (bytes * 8000 / time_elapsed);
            double time = (time_elapsed / maxTime);

            if (i + 1 == graphArray.length()) {
                signal.addValue(IntermediateResult.toLog((long) bitPerSec), time, SmoothGraph.FLAG_ALIGN_RIGHT);
            } else {
                signal.addValue(IntermediateResult.toLog((long) bitPerSec), time,
                        i == 0 ? SmoothGraph.FLAG_ALIGN_LEFT : SmoothGraph.FLAG_NONE);
            }
        }
    }
}

From source file:com.ternup.caddisfly.fragment.ResultFragment.java

public void postResult(final String url) {

    RequestParams params = new RequestParams();
    TimeZone tz = TimeZone.getTimeZone("UTC");
    final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
    df.setTimeZone(tz);/*from w  ww  .  ja v  a  2  s  . c  om*/

    final ArrayList<String> filePaths = FileUtils.getFilePaths(getActivity(), folderName, "/small/",
            mLocationId);
    File myFile = new File(filePaths.get(0));
    String date = df.format(DateUtils.getDateFromFilename(myFile.getName()));

    params.put("date", date);
    String deviceId = Build.MANUFACTURER + " " + Build.MODEL;
    if (deviceId.length() > 32) {
        deviceId = deviceId.substring(1, 32);
    }
    params.put("deviceId", deviceId);
    params.put("type", String.valueOf(mTestTypeId + 1));

    if (wakeLock == null || !wakeLock.isHeld()) {
        PowerManager pm = (PowerManager) getActivity().getApplicationContext()
                .getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP
                | PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
        wakeLock.acquire();
    }

    WebClient.post("tests", params, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String response = responseBody == null ? null : new String(responseBody);
            try {
                JSONObject json = new JSONObject(response);
                final int newId = json.getInt("id");
                if (filePaths.size() > 0) {
                    count = 0;
                    totalCount = filePaths.size();
                    postItem(newId, filePaths);
                }

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

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            Log.d(Globals.DEBUG_TAG, "fail: " + error.getMessage());
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }

                    if (wakeLock != null && wakeLock.isHeld()) {
                        wakeLock.release();
                    }
                }
            });

        }
    });
}

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

public Stat(JSONObject _json) throws MalformedPacketException {

    /**/*from w  w w. j a  va 2s . c  o m*/
     * time
     */
    if (!_json.has("time")) {
        throw new MalformedPacketException("missing time");
    } else {
        time = _json.getString("time");
    }

    /**
     * lati
     */
    if (!_json.has("lati")) {
        lati = Double.MAX_VALUE;
    } else {
        lati = _json.getDouble("lati");
    }

    /**
     * longi
     */
    if (!_json.has("longi")) {
        lati = Double.MAX_VALUE;
    } else {
        longi = _json.getDouble("longi");
    }

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

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

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

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

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

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

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

}

From source file:com.clearner.youtube.Playlist.java

public Playlist(JSONObject jsonPlaylist) throws JSONException {
    pages = new ArrayList<Page>();

    JSONObject pageInfo = jsonPlaylist.getJSONObject("pageInfo");
    totalResults = pageInfo.getInt("totalResults");
    resultsPerPage = pageInfo.getInt("resultsPerPage");

    addPage(jsonPlaylist);//from   w w w  . ja  v a2 s  . c o m
}

From source file:com.hunch.api.HunchQuestion.java

static HunchQuestion buildFromJSON(JSONObject json) {
    final HunchQuestion.Builder builder = getBuilder();
    final HunchResponse.Builder respBuilder = HunchResponse.getBuilder();

    // build the HunchQuestion object
    int id = Integer.MIN_VALUE, topicId = Integer.MIN_VALUE;
    String text = "", imgUrl = "";
    JSONArray jsonResIds;/*w w  w  .j  av  a 2s .c o m*/
    List<HunchResponse> responses = new ArrayList<HunchResponse>();

    try {
        jsonResIds = json.getJSONArray("responseIds");
    } catch (JSONException e) {
        throw new RuntimeException("Couldn't build HunchQuestion!", e);
    }

    for (int i = 0; i < jsonResIds.length(); i++) {
        JSONObject obj = new JSONObject();
        try {
            obj.put("responseIds", jsonResIds);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        respBuilder.init(obj);

        try {
            respBuilder.setId(jsonResIds.getInt(i));
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        responses.add(respBuilder.buildForQuestion());
    }

    try {
        String tId = json.getString("topicId");

        try {
            topicId = Integer.parseInt(tId);
        } catch (NumberFormatException e) {
            if (tId.equals("THAY")) {
                // Teach Hunch About You!
                topicId = THAY_TOPIC_ID;
            } else {
                // some other cause of the NFE
                throw new RuntimeException("Couldn't build HunchQuestion!", e);
            }
        }

        id = json.getInt("id");
        text = json.getString("text");
        imgUrl = json.getString("imageUrl");

    } catch (NumberFormatException e) {
        throw new RuntimeException("Couldn't build HunchQuestion!", e);
    } catch (JSONException e) {
        throw new RuntimeException("Couldn't build HunchQuestion!", e);
    } finally {
        builder.init(json).setId(id).setTopicId(topicId).setText(text).setImageUrl(imgUrl)
                .setResponses(responses);
    }

    return builder.build();
}

From source file:com.norman0406.slimgress.API.Knobs.NearbyPortalKnobs.java

public NearbyPortalKnobs(JSONObject json) throws JSONException {
    super(json);/*from   ww w.  j av a2  s  .  co  m*/

    mRepopulateDistanceMeters = json.getInt("repopulateDistanceMeters");
    mRepopulateTimeMilliseconds = Integer.parseInt(json.getString("repopulateTimeMilliseconds"));
}

From source file:damian.hashmap.MyActivity.java

public void generateLicenses() throws JSONException {

    JSONArray obj = new JSONArray(loadJSONFromAsset());
    for (int i = 0; i < obj.length(); i++) {
        JSONObject obj2 = obj.getJSONObject(i);
        String name = obj2.getString("name");
        int dni = obj2.getInt("dni");
        JSONObject license = obj2.getJSONObject("license");
        License license1 = new License();
        if (license.length() > 0) {
            license1.setName(name);//from   ww w.j  a v a 2 s . c o m
            long since = license.getLong("since");
            long until = license.getLong("until");
            license1.setSince(since);
            license1.setUntil(until);
        }
        Person person = new Person();
        person.setDni(dni);
        person.setName(name);
        if (license.length() > 0) {
            licences.put(person, license1);
        } else {
            licences.put(person, null);
        }
    }
}

From source file:com.fvd.nimbus.MainActivity.java

@Override
public void onTaskComplete(String result, String action) {
    if (result.length() == 0)
        return;//  ww  w.  j  a va2s . co m
    try {
        JSONObject root = new JSONObject(result);
        int error = root.getInt("errorCode");
        //error=-6;

        if (error == 0) {
            if (action.equalsIgnoreCase("user:auth")) {
                final String sessionId = root.getJSONObject("body").getString("sessionid");
                Editor e = prefs.edit();
                e.putString("userMail", userMail);
                e.putString("userPass", userPass);
                e.putString("sessionId", sessionId);
                e.commit();

                appSettings.sessionId = sessionId;
                appSettings.userMail = userMail;
                appSettings.userPass = userPass;

                Toast.makeText(getApplicationContext(), "user authorized", Toast.LENGTH_LONG).show();
            } else if (action.equalsIgnoreCase("user:authstate")) {
                boolean auth = root.getJSONObject("body").getBoolean("authorized");
                Toast.makeText(getApplicationContext(), "user " + (auth ? "authorized" : "not authorized"),
                        Toast.LENGTH_LONG).show();
                if (!auth) {
                    appSettings.sessionId = "";
                    Editor e = prefs.edit();
                    e.putString("userMail", userMail);
                    e.putString("userPass", "");
                    e.putString("sessionId", appSettings.sessionId);
                    e.commit();
                    showLogin();
                }
            } else if ("user_register".equals(action)) {
                sendRequest("user:auth",
                        String.format("\"email\":\"%s\",\"password\":\"%s\"", userMail, userPass));
            }
        } else {
            if (error == -6) {
                showLogin();
                /*if(userMail.length()>0 && userPass.length()>0){
                   sendRequest("user:auth", String.format("\"email\":\"%s\",\"password\":\"%s\"",userMail,userPass));
                } else showLogin();*/
            } else
                Toast.makeText(getApplicationContext(),
                        String.format("Error: %s", serverHelper.errorMsg(error)), Toast.LENGTH_LONG).show();
        }
    } catch (Exception Ex) {
    }
}

From source file:com.android.cast.demo.GameMessageStream.java

/**
 * Processes all JSON messages received from the receiver device and performs the appropriate 
 * action for the message. Recognizable messages are of the form:
 * //from  w  ww .j a  va 2s .c  om
 * <ul>
 * <li> KEY_JOINED: a player joined the current game
 * <li> KEY_MOVED: a player made a move
 * <li> KEY_ENDGAME: the game has ended in one of the END_STATE_* states
 * <li> KEY_ERROR: a game error has occurred
 * <li> KEY_BOARD_LAYOUT_RESPONSE: the board has been laid out in some new configuration
 * </ul>
 * 
 * <p>No other messages are recognized.
 */
@Override
public void onMessageReceived(JSONObject message) {
    try {
        Log.d(TAG, "onMessageReceived: " + message);
        if (message.has(KEY_EVENT)) {
            String event = message.getString(KEY_EVENT);
            if (KEY_JOINED.equals(event)) {
                Log.d(TAG, "JOINED");
                try {
                    String player = message.getString(KEY_PLAYER);
                    String opponentName = message.getString(KEY_OPPONENT);
                    onGameJoined(player, opponentName);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (KEY_MOVED.equals(event)) {
                Log.d(TAG, "MOVED");
                try {
                    String player = message.getString(KEY_PLAYER);
                    int row = message.getInt(KEY_ROW);
                    int column = message.getInt(KEY_COLUMN);
                    boolean isGameOver = message.getBoolean(KEY_GAME_OVER);
                    onGameMove(player, row, column, isGameOver);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (KEY_ENDGAME.equals(event)) {
                Log.d(TAG, "ENDGAME");
                try {
                    String endState = message.getString(KEY_END_STATE);
                    int winningLocation = -1;
                    if (END_STATE_ABANDONED.equals(endState) == false) {
                        winningLocation = message.getInt(KEY_WINNING_LOCATION);
                    }
                    onGameEnd(endState, winningLocation);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (KEY_ERROR.equals(event)) {
                Log.d(TAG, "ERROR");
                try {
                    String errorMessage = message.getString(KEY_MESSAGE);
                    onGameError(errorMessage);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (KEY_BOARD_LAYOUT_RESPONSE.equals(event)) {
                Log.d(TAG, "Board Layout");
                int[][] boardLayout = new int[3][3];
                try {
                    JSONArray boardJSONArray = message.getJSONArray(KEY_BOARD);
                    for (int i = 0; i < 3; ++i) {
                        for (int j = 0; j < 3; ++j) {
                            boardLayout[i][j] = boardJSONArray.getInt(i * 3 + j);
                        }
                    }
                    onGameBoardLayout(boardLayout);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        } else {
            Log.w(TAG, "Unknown message: " + message);
        }
    } catch (JSONException e) {
        Log.w(TAG, "Message doesn't contain an expected key.", e);
    }
}

From source file:fr.openbike.android.io.RemoteNetworksHandler.java

@Override
public Object parse(JSONObject json, OpenBikeDBAdapter dbAdapter) throws JSONException, IOException {
    JSONArray jsonNetworks = json.getJSONArray("networks");
    ArrayList<Network> networks = new ArrayList<Network>();
    JSONObject jsonNetwork;
    for (int i = 0; i < jsonNetworks.length(); i++) {
        jsonNetwork = jsonNetworks.getJSONObject(i);
        networks.add(new Network(jsonNetwork.getInt(Network.ID), jsonNetwork.getString(Network.NAME),
                jsonNetwork.getString(Network.CITY), jsonNetwork.getString(Network.SERVER),
                jsonNetwork.getString(Network.SPECIAL_NAME), jsonNetwork.getDouble(Network.LONGITUDE),
                jsonNetwork.getDouble(Network.LATITUDE)));
    }// www.j av a 2s. com
    return networks;
}