Example usage for org.json JSONObject getDouble

List of usage examples for org.json JSONObject getDouble

Introduction

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

Prototype

public double getDouble(String key) throws JSONException 

Source Link

Document

Get the double value associated with a key.

Usage

From source file:org.droidparts.test.testcase.serialize.JSONTestCase.java

public void testPrimitives() throws Exception {
    JSONSerializer<Primitives> serializer = makeSerializer(Primitives.class);
    Primitives primitives = serializer.deserialize(getPrimitives());
    assertNotNull(primitives.strArr);/* w  w w  .ja v  a  2  s .c o m*/
    assertEquals(9000, (long) primitives.longList.get(0));
    //
    JSONObject obj = serializer.serialize(primitives);
    //
    assertEquals(1, obj.getInt("int1"));
    assertEquals(2, obj.getInt("int2"));
    assertEquals(0.5, obj.getDouble("float1"));
    assertEquals(2.5, obj.getDouble("float2"));
    assertEquals(true, obj.getBoolean("boolean1"));
    assertEquals(true, obj.getBoolean("boolean2"));
    assertEquals(true, obj.getBoolean("boolean3"));
    assertEquals(false, obj.getBoolean("boolean4"));
    assertEquals("str", obj.getString("string1"));
    assertEquals(2, obj.getJSONArray("string_array").length());
    assertEquals("two", obj.getJSONArray("string_array").getString(1));
}

From source file:com.mjhram.ttaxi.gcm_client.MyGcmListenerService.java

/**
 * Called when message is received./*from  w  w  w . java2  s .  co m*/
 *
 * @param from SenderID of the sender.
 * @param data Data bundle containing message data as key/value pairs.
 *             For Set of keys use data.keySet().
 */
// [START receive_message]
@Override
public void onMessageReceived(String from, Bundle data) {
    String message = data.getString("message");
    Log.d(TAG, "From: " + from);
    Log.d(TAG, "Message: " + message);

    if (from.startsWith("/topics/")) {
        // message received from some topic.
    } else {
        try {
            String tag;
            JSONObject msgObj;

            msgObj = new JSONObject(message);
            tag = msgObj.getString("tag");

            if (tag.equalsIgnoreCase("drvId")) {
                int drvId = msgObj.getInt("data");//Integer.parseInt(message);
                EventBus.getDefault().post(new ServiceEvents.TRequestAccepted(drvId));
                message = Integer.toString(drvId);
                /*Intent intent = new Intent(Constants.UPDATE_REQ);
                //put whatever data you want to send, if any
                intent.putExtra("drvId", drvId);
                //send broadcast
                getApplicationContext().sendBroadcast(intent);*/
                // normal downstream message.
            } else if (tag.equalsIgnoreCase("treqState")) {
                String state = msgObj.getString("data");//Integer.parseInt(message);
                EventBus.getDefault().post(new ServiceEvents.TRequestUpdated(state));
                message = getString(R.string.gcmClientReqState) + state;
                /*Intent intent = new Intent(Constants.UPDATE_REQ);
                //put whatever data you want to send, if any
                intent.putExtra("drvId", drvId);
                //send broadcast
                getApplicationContext().sendBroadcast(intent);*/
                // normal downstream message.
            } else if (tag.equalsIgnoreCase("drvLoc")) {
                DriverInfo driverInfo = new DriverInfo();
                driverInfo.driverId = msgObj.getInt("drvId");
                driverInfo.latitude = msgObj.getDouble("lat");
                driverInfo.longitude = msgObj.getDouble("lng");

                EventBus.getDefault().post(new ServiceEvents.DriverLocationUpdate(driverInfo));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    sendNotification(message);
    // [END_EXCLUDE]
}

From source file:com.piggate.sdk.PiggateOffers.java

public PiggateOffers(JSONObject object) {
    try {/* ww w  .ja  v a 2  s. c om*/
        _id = object.getString("_id");
    } catch (JSONException e) {
    }
    try {
        _name = object.getString("name");
    } catch (JSONException e) {
    }
    try {
        _description = object.getString("description");
    } catch (JSONException e) {

    }
    try {
        _price = object.getDouble("price");
    } catch (JSONException e) {
    }
    try {
        _currency = object.getString("currency");
    } catch (JSONException e) {
    }
    try {
        _imgURL = object.getString("img");
    } catch (JSONException e) {
    }
    try {
        _exchangeID = object.getString("exchanged");
    } catch (JSONException e) {
    }
    try {
        _token = object.getString("token_key");
    } catch (JSONException e) {
    }

    JSONObject aux = null;
    try {
        aux = object.getJSONObject("position");
        _latitude = aux.getDouble("latitude");
        _longitude = aux.getDouble("length"); //Will be changed to "longitude"
    } catch (JSONException e) {
    }
}

From source file:org.wso2.appmanager.integration.test.cases.RatingTestCase.java

@Test(description = TEST_DESCRIPTION)
public void testWebAppRating() throws Exception {
    HttpResponse response = appmPublisherRestClient.webAppCreate(appName, context, appVersion, trackingCode,
            userName);/*from ww w .  j  a v a  2  s  .c o  m*/
    JSONObject responseData = new JSONObject(response.getData());
    String uuid = responseData.getString(AppmTestConstants.ID);
    appmPublisherRestClient.publishWebApp(uuid);

    final int ratingValue1 = 3;

    // Subscribe and rate to app from admin user
    HttpResponse adminUserResponse = subscribeAndRateApplication(adminUser, appName, userName, appVersion, uuid,
            ratingValue1);
    JSONObject responseData1 = new JSONObject(adminUserResponse.getData());
    Assert.assertEquals(adminUserResponse.getResponseCode(), 200, "Response code mismatch");
    Assert.assertEquals(responseData1.getDouble(AppmTestConstants.USER), 3.0,
            "Error while rating the web application as user : " + userName);
    Assert.assertEquals(responseData1.getDouble(AppmTestConstants.AVERAGE), 3.0,
            "Error while retrieving the average rating for user : " + userName);

    User testUser = appMServer.getSuperTenant().getTenantUser("testuser1");
    final int ratingValue2 = 5;

    // Subscribe and rate to app from testuser1
    HttpResponse testUserResponse = subscribeAndRateApplication(testUser, appName, userName, appVersion, uuid,
            ratingValue2);
    Assert.assertEquals(testUserResponse.getResponseCode(), 200, "Response code mismatch");
    JSONObject responseData2 = new JSONObject(testUserResponse.getData());
    Assert.assertEquals(responseData2.getDouble("user"), 5.0,
            "Error while rating the web application as user : " + testUser.getUserName());
    Assert.assertEquals(responseData2.getDouble("average"), 4.0,
            "Error while retrieving the average rating for user : " + testUser.getUserName());

}

From source file:com.nokia.example.capturetheflag.network.model.Game.java

public Game(final JSONObject jsonObj) throws JSONException {
    this(jsonObj.getInt(ModelConstants.ID_KEY));
    setName(jsonObj.getString(ModelConstants.NAME_KEY));
    JSONArray jsonArray = jsonObj.getJSONArray(ModelConstants.PLAYERS_KEY);

    for (int i = 0; i < jsonArray.length(); i++) {
        Player p = new Player(jsonArray.getJSONObject(i));
        addPlayer(p);//from  w w  w .j av  a2s .  c  o  m
    }

    JSONObject redflag = jsonObj.getJSONObject(ModelConstants.RED_FLAG_KEY);
    JSONObject blueflag = jsonObj.getJSONObject(ModelConstants.BLUE_FLAG_KEY);

    mRedFlag = new Flag(redflag.getDouble(ModelConstants.LATITUDE_KEY),
            redflag.getDouble(ModelConstants.LONGITUDE_KEY));
    mBlueFlag = new Flag(blueflag.getDouble(ModelConstants.LATITUDE_KEY),
            blueflag.getDouble(ModelConstants.LONGITUDE_KEY));

    mIsPremium = jsonObj.optBoolean(ModelConstants.IS_PREMIUM_KEY, false);
}

From source file:org.ExtendedAlpha.Nexus.TacoSerialization.EconomySerialization.java

public static void setEconomy(Economy econ, JSONObject data, Player player) {
    try {/*w  ww.j  a v a  2  s . c o m*/
        if (data.has("bank-balance")) {
            econ.bankWithdraw(player.getName(), econ.bankBalance(player.getName()).balance);
            econ.bankDeposit(player.getName(), data.getDouble("bank-balance"));
        }

        econ.withdrawPlayer(String.valueOf(player), econ.getBalance(String.valueOf(player)));
        econ.depositPlayer(String.valueOf(player), data.getDouble("balance"));
    } catch (JSONException ex) {
        ex.printStackTrace();
    }
}

From source file:app.com.example.kiran.sunshine.FetchWeatherTask.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 * <p/>/*from  w ww  .  j a va  2  s . c om*/
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.
 */
private void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException {

    // Now we have a String representing the complete forecast in JSON Format.
    // Fortunately parsing is easy:  constructor takes the JSON string and converts it
    // into an Object hierarchy for us.

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";

    // Location coordinate
    final String OWM_LATITUDE = "lat";
    final String OWM_LONGITUDE = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    try {
        JSONObject forecastJson = new JSONObject(forecastJsonStr);
        JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

        JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
        String cityName = cityJson.getString(OWM_CITY_NAME);

        JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD);
        double cityLatitude = cityCoord.getDouble(OWM_LATITUDE);
        double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE);

        long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

        // Insert the new weather information into the database
        Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());

        // OWM returns daily forecasts based upon the local time of the city that is being
        // asked for, which means that we need to know the GMT offset to translate this data
        // properly.

        // Since this data is also sent in-order and the first day is always the
        // current day, we're going to take advantage of that to get a nice
        // normalized UTC date for all of our weather.

        Time dayTime = new Time();
        dayTime.setToNow();

        // we start at the day returned by local time. Otherwise this is a mess.
        int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

        // now we work exclusively in UTC
        dayTime = new Time();

        for (int i = 0; i < weatherArray.length(); i++) {
            // These are the values that will be collected.
            long dateTime;
            double pressure;
            int humidity;
            double windSpeed;
            double windDirection;

            double high;
            double low;

            String description;
            int weatherId;

            // Get the JSON object representing the day
            JSONObject dayForecast = weatherArray.getJSONObject(i);

            // Cheating to convert this to UTC time, which is what we want anyhow
            dateTime = dayTime.setJulianDay(julianStartDay + i);

            pressure = dayForecast.getDouble(OWM_PRESSURE);
            humidity = dayForecast.getInt(OWM_HUMIDITY);
            windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
            windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

            // Description is in a child array called "weather", which is 1 element long.
            // That element also contains a weather code.
            JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
            description = weatherObject.getString(OWM_DESCRIPTION);
            weatherId = weatherObject.getInt(OWM_WEATHER_ID);

            // Temperatures are in a child object called "temp".  Try not to name variables
            // "temp" when working with temperature.  It confuses everybody.
            JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
            high = temperatureObject.getDouble(OWM_MAX);
            low = temperatureObject.getDouble(OWM_MIN);

            ContentValues weatherValues = new ContentValues();

            weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId);
            weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime);
            weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity);
            weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure);
            weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
            weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection);
            weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high);
            weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low);
            weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description);
            weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId);

            cVVector.add(weatherValues);
        }

        // add to database
        if (cVVector.size() > 0) {
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);
            mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
        }

        // Sort order:  Ascending, by date.
        String sortOrder = WeatherEntry.COLUMN_DATE + " ASC";
        Uri weatherForLocationUri = WeatherEntry.buildWeatherLocationWithStartDate(locationSetting,
                System.currentTimeMillis());

        // Students: Uncomment the next lines to display what what you stored in the bulkInsert
        Cursor cur = mContext.getContentResolver().query(weatherForLocationUri, null, null, null, sortOrder);

        cVVector = new Vector<ContentValues>(cur.getCount());
        if (cur.moveToFirst()) {
            do {
                ContentValues cv = new ContentValues();
                DatabaseUtils.cursorRowToContentValues(cur, cv);
                cVVector.add(cv);
            } while (cur.moveToNext());
        }

        Log.d(LOG_TAG, "FetchWeatherTask Complete. " + cVVector.size() + " Inserted");

        //String resultStrs = convertContentValuesToUXFormat(cur);
        //return resultStrs;

    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    } catch (Exception e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
    //return null;
}

From source file:com.hichinaschool.flashcards.libanki.Sched.java

/**
 * @param ease 1=no, 2=yes, 3=remove/*from  w w w  .jav  a2  s  .  c  o  m*/
 */
private void _answerLrnCard(Card card, int ease) {
    JSONObject conf = _lrnConf(card);
    int type;
    if (card.getODid() != 0 && !card.getWasNew()) {
        type = 3;
    } else if (card.getType() == 2) {
        type = 2;
    } else {
        type = 0;
    }
    boolean leaving = false;
    // lrnCount was decremented once when card was fetched
    int lastLeft = card.getLeft();
    // immediate graduate?
    if (ease == 3) {
        _rescheduleAsRev(card, conf, true);
        leaving = true;
        // graduation time?
    } else if (ease == 2 && (card.getLeft() % 1000) - 1 <= 0) {
        _rescheduleAsRev(card, conf, false);
        leaving = true;
    } else {
        // one step towards graduation
        if (ease == 2) {
            // decrement real left count and recalculate left today
            int left = (card.getLeft() % 1000) - 1;
            try {
                card.setLeft(_leftToday(conf.getJSONArray("delays"), left) * 1000 + left);
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
            // failed
        } else {
            card.setLeft(_startingLeft(card));
            boolean resched = _resched(card);
            if (conf.has("mult") && resched) {
                // review that's lapsed
                try {
                    card.setIvl(Math.max(Math.max(1, (int) (card.getIvl() * conf.getDouble("mult"))),
                            conf.getInt("minInt")));
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            } else {
                // new card; no ivl adjustment
                // pass
            }
            if (resched && card.getODid() != 0) {
                card.setODue(mToday + 1);
            }
        }
        int delay = _delayForGrade(conf, card.getLeft());
        if (card.getDue() < Utils.now()) {
            // not collapsed; add some randomness
            delay *= (1 + (new Random().nextInt(25) / 100));
        }
        // TODO: check, if type for second due is correct
        card.setDue((int) (Utils.now() + delay));

        // due today?
        if (card.getDue() < mDayCutoff) {
            mLrnCount += card.getLeft() / 1000;
            // if the queue is not empty and there's nothing else to do, make
            // sure we don't put it at the head of the queue and end up showing
            // it twice in a row
            card.setQueue(1);
            if (!mLrnQueue.isEmpty() && mRevCount == 0 && mNewCount == 0) {
                long smallestDue = mLrnQueue.getFirst()[0];
                card.setDue(Math.max(card.getDue(), smallestDue + 1));
            }
            _sortIntoLrn(card.getDue(), card.getId());
        } else {
            // the card is due in one or more days, so we need to use the day learn queue
            long ahead = ((card.getDue() - mDayCutoff) / 86400) + 1;
            card.setDue(mToday + ahead);
            card.setQueue(3);
        }
    }
    _logLrn(card, ease, conf, leaving, type, lastLeft);
}

From source file:com.hichinaschool.flashcards.libanki.Sched.java

private int _nextLapseIvl(Card card, JSONObject conf) {
    try {/*from  w w w. j a  v  a2 s  .c  o m*/
        return Math.max(conf.getInt("minInt"), (int) (card.getIvl() * conf.getDouble("mult")));
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.hichinaschool.flashcards.libanki.Sched.java

/**
 * Ideal next interval for CARD, given EASE.
 *//*from  ww w . j a  v  a2 s  .  co m*/
private int _nextRevIvl(Card card, int ease) {
    try {
        long delay = _daysLate(card);
        int interval = 0;
        JSONObject conf = _revConf(card);
        double fct = card.getFactor() / 1000.0;
        int ivl2 = _constrainedIvl((int) ((card.getIvl() + delay / 4) * 1.2), conf, card.getIvl());
        int ivl3 = _constrainedIvl((int) ((card.getIvl() + delay / 2) * fct), conf, ivl2);
        int ivl4 = _constrainedIvl((int) ((card.getIvl() + delay) * fct * conf.getDouble("ease4")), conf, ivl3);
        if (ease == 2) {
            interval = ivl2;
        } else if (ease == 3) {
            interval = ivl3;
        } else if (ease == 4) {
            interval = ivl4;
        }
        // interval capped?
        return Math.min(interval, conf.getInt("maxIvl"));
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}