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:ru.jkff.antro.ReportReader.java

private Trace toTrace(JSONObject root) throws JSONException {
    String name = root.getJSONObject("call").getString("name");
    Trace t = Trace.newRoot(name, new OurLocation(name, 0));
    double total = root.has("total") ? root.getDouble("total") : 0;
    double own = root.has("own") ? root.getDouble("own") : 0;

    t.totalTime = total;//from   www  .  j  ava 2  s. co m
    t.childrenTime = total - own;

    if (root.has("children")) {
        JSONArray children = root.getJSONArray("children");
        for (int i = 0; i < children.length(); ++i) {
            t.addChild(toTrace(children.getJSONObject(i), t));
        }
    }
    return t;
}

From source file:ru.jkff.antro.ReportReader.java

private Trace toTrace(JSONObject root, Trace parent) throws JSONException {
    Call call = toCall(root.getJSONObject("call"));
    Trace t = new Trace(parent, call);
    double total = root.has("total") ? root.getDouble("total") : 0;
    double own = root.has("own") ? root.getDouble("own") : 0;

    t.totalTime = total;//from w ww .  ja v  a  2 s  .c o m
    t.childrenTime = total - own;

    if (root.has("children")) {
        JSONArray children = root.getJSONArray("children");
        for (int i = 0; i < children.length(); ++i) {
            t.addChild(toTrace(children.getJSONObject(i), t));
        }
    }
    return t;
}

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

public Player(JSONObject jsonObject) throws JSONException {
    this(jsonObject.getInt(ModelConstants.ID_KEY), jsonObject.getString(ModelConstants.NAME_KEY));
    mLatitude = jsonObject.getDouble(ModelConstants.LATITUDE_KEY);
    mLongitude = jsonObject.getDouble(ModelConstants.LONGITUDE_KEY);
    mTeam = jsonObject.getString(ModelConstants.TEAM_KEY);
    mRegId = jsonObject.getString(ModelConstants.REGISTRATION_ID_KEY);
}

From source file:permit.Address.java

void getMasterAddrInfo(String url2) {
    ////from   ww  w.  j  av  a2s .  co m
    String back = "";
    String url = url2 + "addresses/verify.php?format=xml&address=";
    DefaultHttpClient httpclient = new DefaultHttpClient();
    String addrStr = "";
    String streetAddress = "";
    double addr_lat = 0, addr_long = 0;
    try {
        addrStr = java.net.URLEncoder.encode(address, "UTF-8");
        addrStr += "+Bloomington";
        url += addrStr;
        if (debug) {
            logger.debug(url);
        }
        HttpGet httpget = new HttpGet(url);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpget, responseHandler);
        logger.debug("----------------------------------------");
        logger.debug(responseBody);
        logger.debug("----------------------------------------");

        JSONObject jObj = org.json.XML.toJSONObject(responseBody);
        // System.err.println(jObj.toString());
        if (jObj.has("address")) {
            JSONObject jObj2 = jObj.getJSONObject("address");
            if (jObj2.has("streetAddress")) {
                street_address = jObj2.getString("streetAddress");
                // System.err.println(street_address);               
            }
            if (jObj2.has("latitude")) {
                addr_lat = jObj2.getDouble("latitude");
            }
            if (jObj2.has("longitude")) {
                addr_long = jObj2.getDouble("longitude");
            }
            if (addr_lat != 0) {
                loc_lat = "" + addr_lat;
                loc_long = "" + addr_long;
            }
            // System.err.println(streetAddress+" "+addr_lat+" "+addr_long);
        }
    } catch (Exception ex) {
        logger.error(" " + ex);
    }
}

From source file:com.mio.jrdv.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.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us./*  w  w w.  j av a  2s  . co  m*/
 */
private String[] 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);
        }

        ////////////////////////////////////////////////////////////////////////////////////////////
        ////// ////////////////////////////////////////////////////////////////////////////////////////////
        //////NO SE USA SE PASA AL FORECAST ADAPTER
        // The lines in getWeatherDataFromJson where we requery the database after the insert.
        //vamoa acambiarlo por el nuevo FroreCastAdapter!!:
        ////////////////////////////////////////////////////////////////////////////////////////////

        //            // add to database
        //            if ( cVVector.size() > 0 ) {
        //                // Student: call bulkInsert to add the weatherEntries to the database here
        //
        //                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
        //            //esto no hace nada !!lo que hace es que inserte 0!!!! si no lo hacemos por medio un 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(cVVector);
        //            return resultStrs;

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

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

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

From source file:com.graphhopper.http.GraphHopperServletWithEleIT.java

@Test
public void testElevation() throws Exception {
    JSONObject json = query(/*from w w w .  j  a  v a2s.  c  o  m*/
            "point=43.730864,7.420771&point=43.727687,7.418737&points_encoded=false&elevation=true");
    JSONObject infoJson = json.getJSONObject("info");
    assertFalse(infoJson.has("errors"));
    JSONObject path = json.getJSONArray("paths").getJSONObject(0);
    double distance = path.getDouble("distance");
    assertTrue("distance wasn't correct:" + distance, distance > 2500);
    assertTrue("distance wasn't correct:" + distance, distance < 2700);

    JSONObject cson = path.getJSONObject("points");
    assertTrue("no elevation?", cson.toString().indexOf("[7.421392,43.7307,66]") >= 0);
}

From source file:com.graphhopper.http.GraphHopperServletWithEleIT.java

@Test
public void testNoElevation() throws Exception {
    // default is elevation=false
    JSONObject json = query("point=43.730864,7.420771&point=43.727687,7.418737&points_encoded=false");
    JSONObject infoJson = json.getJSONObject("info");
    assertFalse(infoJson.has("errors"));
    JSONObject path = json.getJSONArray("paths").getJSONObject(0);
    double distance = path.getDouble("distance");
    assertTrue("distance wasn't correct:" + distance, distance > 2500);
    assertTrue("distance wasn't correct:" + distance, distance < 2700);
    JSONObject cson = path.getJSONObject("points");
    assertTrue("Elevation should not be included!", cson.toString().indexOf("[7.421392,43.7307]") >= 0);

    // disable elevation
    json = query("point=43.730864,7.420771&point=43.727687,7.418737&points_encoded=false&elevation=false");
    infoJson = json.getJSONObject("info");
    assertFalse(infoJson.has("errors"));
    path = json.getJSONArray("paths").getJSONObject(0);
    cson = path.getJSONObject("points");
    assertTrue("Elevation should not be included!", cson.toString().indexOf("[7.421392,43.7307]") >= 0);
}

From source file:ub.botiga.data.Product.java

public Product(JSONObject obj) throws JSONException {
    this.mName = obj.getString("name");
    this.mType = Utils.getFileType(obj.getString("type"));
    this.mDescription = obj.getString("desc");
    this.mPrice = (float) obj.getDouble("price");
    this.path = obj.getString("path");
}

From source file:com.worthed.util.LocationUtils.java

/**
 * ????/*  w  w  w.j a v a  2s  .c  om*/
 *
 * @param address ??
 * @return ?
 */
public static double[] getLocationInfo(String address) {
    if (TextUtils.isEmpty(address)) {
        return null;
    }
    if (DEBUG) {
        LogUtils.d(TAG, "address : " + address);
    }
    // HttpClient????
    HttpClient client = new DefaultHttpClient();
    // ????GET
    HttpGet httpGet = new HttpGet(
            "http://maps.google." + "com/maps/api/geocode/json?address=" + address + "ka&sensor=false");
    StringBuilder sb = new StringBuilder();
    try {
        // ???
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        // ????
        InputStream stream = entity.getContent();
        int b;
        // ???
        while ((b = stream.read()) != -1) {
            sb.append((char) b);
        }
        // ??JSONObject
        JSONObject jsonObject = new JSONObject(sb.toString());
        // JSONObject??location
        JSONObject location = jsonObject.getJSONArray("results").getJSONObject(0).getJSONObject("geometry")
                .getJSONObject("location");
        // ???
        double longitude = location.getDouble("lng");
        // ??
        double latitude = location.getDouble("lat");
        if (DEBUG) {
            LogUtils.d(TAG, "location : (" + longitude + "," + latitude + ")");
        }
        // ????double[]
        return new double[] { longitude, latitude };
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:de.dekarlab.moneybuilder.model.parser.JsonBookLoader.java

/**
 * Parse account value.//from  w  ww  .j a va  2s.c  om
 * 
 * @param jsonNewAccount
 * @param acnt
 */
protected static void parseAccountValues(JSONObject jsonNewAccount, Account acnt) {
    JSONArray jsonPeriodBudgetList = jsonNewAccount.optJSONArray("periodBudget");
    JSONArray jsonPeriodValueList = jsonNewAccount.optJSONArray("periodValue");
    if (jsonPeriodBudgetList != null) {
        for (int j = 0; j < jsonPeriodBudgetList.length(); j++) {
            JSONObject jsonPeriodBudget = jsonPeriodBudgetList.getJSONObject(j);
            acnt.setBudget(jsonPeriodBudget.getString("periodId"), jsonPeriodBudget.getDouble("budget"));
        }
    }
    if (jsonPeriodValueList != null) {
        for (int j = 0; j < jsonPeriodValueList.length(); j++) {
            JSONObject jsonPeriodValue = jsonPeriodValueList.getJSONObject(j);
            acnt.setValue(jsonPeriodValue.getString("periodId"),
                    parseValue(jsonPeriodValue.optJSONObject("value")));

        }
    }
}