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:fr.immotronic.ubikit.pems.enocean.impl.item.data.EEP070401DataImpl.java

public static EEP070401DataImpl constructDataFromRecord(JSONObject lastKnownData) {
    if (lastKnownData == null)
        return new EEP070401DataImpl(Float.MIN_VALUE, Float.MIN_VALUE, null);

    try {//from  w  ww .j  a v a2s .  c  om
        float temperature = (float) lastKnownData.getDouble("temperature");
        float relativeHumidity = (float) lastKnownData.getDouble("relativeHumidity");
        Date date = new Date(lastKnownData.getLong("date"));

        return new EEP070401DataImpl(temperature, relativeHumidity, date);
    } catch (JSONException e) {
        Logger.error(LC.gi(), null,
                "constructDataFromRecord(): An exception while building a sensorData from a JSONObject SHOULD never happen. Check the code !",
                e);
        return new EEP070401DataImpl(Float.MIN_VALUE, Float.MIN_VALUE, null);
    }
}

From source file:org.mixare.data.convert.PanoramioDataProcessor.java

/**
 * Reads and creates Markers based on Panoramio API returned results.
 * Example JSON:/*w  w  w  .j a v  a 2 s  .c om*/
 * 
 * <pre>
 *  {
 *  "count": 773840,"photos": [
 *     {
 *        "photo_id": 532693,
 *        "photo_title": "Wheatfield in afternoon light",
 *        "photo_url": "http://www.panoramio.com/photo/532693",
 *        "photo_file_url": "http://static2.bareka.com/photos/medium/532693.jpg",
 *        "longitude": 11.280727,
 *        "latitude": 59.643198,
 *        "width": 500,
 *        "height": 333,
 *        "upload_date": "22 January 2007",
 *        "owner_id": 39160,
 *        "owner_name": "Snemann",
 *        "owner_url": "http://www.panoramio.com/user/39160",
 *  }, ...
 * </pre>
 * 
 * @param rawData raw JSON string to be parsed as objects
 * @param taskId (unused)
 * @param color the color of the markers
 * @return List<Marker> List of Markers
 */
@Override
public List<Marker> load(String rawData, int taskId, int color) throws JSONException {
    final List<Marker> markers = new ArrayList<>();
    final JSONObject root = convertToJSON(rawData);
    JSONArray dataArray = root.getJSONArray("photos");
    int top = Math.min(MAX_JSON_OBJECTS, dataArray.length());

    Log.i(Config.TAG, "Processing Panoramio Results ...");

    for (int i = 0; i < top; i++) {
        JSONObject jo = dataArray.getJSONObject(i);

        if (jo.has("photo_id") && jo.has("latitude") && jo.has("longitude") && jo.has("photo_file_url")) {

            // For Panoramio elevation, generate a random number ranged [30
            // -
            // 120]
            // @TODO find better way
            // http://www.geonames.org/export/web-services.html#astergdem
            // http://asterweb.jpl.nasa.gov/gdem.asp
            // final Random elevation = new Random();
            Double lat = jo.getDouble("latitude");
            Double lng = jo.getDouble("longitude");
            // Elevation elevationObj = new Elevation();
            Double elevation = 0.0;
            String title = HtmlUnescape.unescapeHTML(jo.getString("photo_title"));
            String imageOwner = jo.getString("owner_name");
            if (title.trim().isEmpty()) {
                title = "Photo of " + imageOwner;
            }

            Marker ma = new MarkerBuilder().setId(jo.getString("photo_id")).setTitle(title).setLatitude(lat)
                    .setLongitude(lng).setAltitude(elevation)
                    // (elevation.nextInt(90) + 30), // @TODO elevation
                    // level for Panoramio
                    // imageOwner
                    .setDisplayType(overrideMarkerDisplayType).setPageURL(jo.getString("photo_url"))
                    .setColor(color).setImageURL(jo.getString("photo_file_url")).build();

            if (ma != null) {
                markers.add(ma);
            }
        }
    }

    // maximum amount of markers to send in one loop
    int maxMarkers = 20;

    // arrays holding latitude and longitude values
    Double[] lats;
    Double[] lngs;

    // calculate send counts
    double a = Math.ceil(top / maxMarkers);
    for (int i = 0; i < a; i++) {
        // calculate loop counts
        int looper = maxMarkers;
        if (((i + 1) * maxMarkers) > top) {
            looper = top - maxMarkers * i;
        }

        int z = (i * maxMarkers);
        lats = new Double[looper];
        lngs = new Double[looper];
        // Fill array
        int k = 0;
        for (int j = z; j < z + looper; j++) {
            lats[k] = markers.get(j).getLatitude();
            lngs[k] = markers.get(j).getLongitude();
            k++;
        }

        // request
        String[] content = Elevation.getElevation().calcElevations(lats, lngs);

        if (content.length != looper) {
            Log.d("test", "looper(" + looper + ") != length(" + content.length + ")");
        }

        k = 0;
        for (int j = z; j < z + looper; j++) {
            // Fill request data to array
            Marker ma = markers.get(j);
            ma.setAltitude(Double.valueOf(content[k]));
            markers.set(j, ma);
            k++;
        }
    }

    return markers;
}

From source file:entities.JsonParser.java

public static Device createDeviceFromJson(JSONObject json) throws JSONException {
    if (json == null)
        throw new JSONException("Invalid input json");

    String id = (String) json.get("ID");
    String name = (String) json.get("NAME");
    String role = (String) json.get("ROLE");
    double lat = json.getDouble("LATITUDE");
    double lon = json.getDouble("LONGITUDE");
    double lux = json.getDouble("LUMINOSITY");
    double temperature = json.getDouble("TEMPERATURE");
    double[] acceleration = new double[3];

    JSONArray jArr = json.getJSONArray("ACCELERATION");
    if (jArr.length() != 3) {
        throw new JSONException("Invalid acceleration length");
    }/*from w w  w .ja  va2  s  .c o  m*/
    acceleration[0] = jArr.getDouble(0);
    acceleration[1] = jArr.getDouble(1);
    acceleration[2] = jArr.getDouble(2);

    return new Device(id, name, role, lat, lon, lux, temperature, acceleration);
}

From source file:fr.immotronic.ubikit.pems.enocean.impl.item.data.EEP0710xxDataImpl.java

public static EEP0710xxDataImpl constructDataFromRecord(JSONObject lastKnownData) {
    if (lastKnownData == null)
        return new EEP0710xxDataImpl(Float.MIN_VALUE, Float.MIN_VALUE, FanSpeed.UNKNOWN, -1, null,
                DayNightState.UNKNOWN, null);

    try {/*from  w  w w.j av  a2  s  .  c om*/
        float temperature = (float) lastKnownData.getDouble("temperature");
        float relativeHumidity = (float) lastKnownData.getDouble("relativeHumidity");
        FanSpeed fanSpeed = FanSpeed.valueOf(lastKnownData.getString("fanSpeed"));
        int setPoint = lastKnownData.getInt("setPoint");
        long LOPBDate = lastKnownData.optLong("LOPBDate");
        DayNightState dayNightState = DayNightState.valueOf(lastKnownData.getString("dayNightState"));
        ;
        Date date = new Date(lastKnownData.getLong("date"));

        return new EEP0710xxDataImpl(temperature, relativeHumidity, fanSpeed, setPoint,
                (LOPBDate == 0) ? null : new Date(LOPBDate), dayNightState, date);
    } catch (JSONException e) {
        Logger.error(LC.gi(), null,
                "constructDataFromRecord(): An exception while building a sensorData from a JSONObject SHOULD never happen. Check the code !",
                e);
        return new EEP0710xxDataImpl(Float.MIN_VALUE, Float.MIN_VALUE, FanSpeed.UNKNOWN, -1, null,
                DayNightState.UNKNOWN, null);
    }
}

From source file:com.example.sergey.currentweather.app.JSONWeatherParser.java

private static float getFloat(String tagName, JSONObject jObj) {
    float temp = 0;
    try {//ww w  .  jav a 2s . c  om
        temp = (float) jObj.getDouble(tagName);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return temp;
}

From source file:com.clevertrail.mobile.Object_TrailItem.java

public static Object_TrailItem createFromJSON(JSONObject json) {
    if (json == null)
        return null;

    Object_TrailItem trail = new Object_TrailItem();
    try {/*w w w. j  a  v a2  s . c  o  m*/
        trail.sName = json.getString("name");
        trail.sDifficulty = json.getString("difficulty");
        trail.sDistance = json.getString("distance");
        trail.sNearestCity = json.getString("nearestcity");
        trail.sThumbnail = json.getString("image");
        trail.sTimeRequired = json.getString("time");
        trail.sTrailType = json.getString("trailtype");

        //in this order: hike, bicycle, handicap, swim, climb, horse, camp, dog, fish, family
        //todo: should have a better way to maintain the trail uses rather than "remember this order"
        trail.mTrailUse[0] = (json.getString("hike").compareTo("1") == 0);
        trail.mTrailUse[1] = (json.getString("bicycle").compareTo("1") == 0);
        trail.mTrailUse[2] = (json.getString("handicap").compareTo("1") == 0);
        trail.mTrailUse[3] = (json.getString("swim").compareTo("1") == 0);
        trail.mTrailUse[4] = (json.getString("climb").compareTo("1") == 0);
        trail.mTrailUse[5] = (json.getString("horse").compareTo("1") == 0);
        trail.mTrailUse[6] = (json.getString("camp").compareTo("1") == 0);
        trail.mTrailUse[7] = (json.getString("dog").compareTo("1") == 0);
        trail.mTrailUse[8] = (json.getString("fish").compareTo("1") == 0);
        trail.mTrailUse[9] = (json.getString("family").compareTo("1") == 0);

        //map data
        trail.mTrailheadLat = json.getDouble("lat");
        trail.mTrailheadLng = json.getDouble("lng");
    } catch (JSONException e) {

    }

    return trail;
}

From source file:cgeo.geocaching.connector.oc.OkapiClient.java

private static Geocache parseCache(final JSONObject response) {
    final Geocache cache = new Geocache();
    cache.setReliableLatLon(true);/*  w w w .  j  a  va 2  s  .c om*/
    try {

        parseCoreCache(response, cache);

        // not used: url
        final JSONObject owner = response.getJSONObject(CACHE_OWNER);
        cache.setOwnerDisplayName(parseUser(owner));

        cache.getLogCounts().put(LogType.FOUND_IT, response.getInt(CACHE_FOUNDS));
        cache.getLogCounts().put(LogType.DIDNT_FIND_IT, response.getInt(CACHE_NOTFOUNDS));

        if (!response.isNull(CACHE_RATING)) {
            cache.setRating((float) response.getDouble(CACHE_RATING));
        }
        cache.setVotes(response.getInt(CACHE_VOTES));

        cache.setFavoritePoints(response.getInt(CACHE_RECOMMENDATIONS));
        // not used: req_password
        // Prepend gc-link to description if available
        final StringBuilder description = new StringBuilder(500);
        if (!response.isNull("gc_code")) {
            final String gccode = response.getString("gc_code");
            description
                    .append(CgeoApplication.getInstance().getResources().getString(R.string.cache_listed_on,
                            GCConnector.getInstance().getName()))
                    .append(": <a href=\"http://coord.info/").append(gccode).append("\">").append(gccode)
                    .append("</a><br /><br />");
        }
        description.append(response.getString(CACHE_DESCRIPTION));
        cache.setDescription(description.toString());

        // currently the hint is delivered as HTML (contrary to OKAPI documentation), so we can store it directly
        cache.setHint(response.getString(CACHE_HINT));
        // not used: hints

        final JSONArray images = response.getJSONArray(CACHE_IMAGES);
        if (images != null) {
            for (int i = 0; i < images.length(); i++) {
                final JSONObject imageResponse = images.getJSONObject(i);
                final String title = imageResponse.getString(CACHE_IMAGE_CAPTION);
                final String url = absoluteUrl(imageResponse.getString(CACHE_IMAGE_URL), cache.getGeocode());
                // all images are added as spoiler images, although OKAPI has spoiler and non spoiler images
                cache.addSpoiler(new Image(url, title));
            }
        }

        cache.setAttributes(parseAttributes(response.getJSONArray(CACHE_ATTRNAMES),
                response.optJSONArray(CACHE_ATTR_ACODES)));
        cache.setLogs(parseLogs(response.getJSONArray(CACHE_LATEST_LOGS)));
        //TODO: Store license per cache
        //cache.setLicense(response.getString("attribution_note"));
        cache.setWaypoints(parseWaypoints(response.getJSONArray(CACHE_WPTS)), false);
        if (!response.isNull(CACHE_IS_WATCHED)) {
            cache.setOnWatchlist(response.getBoolean(CACHE_IS_WATCHED));
        }
        if (!response.isNull(CACHE_MY_NOTES)) {
            cache.setPersonalNote(response.getString(CACHE_MY_NOTES));
            cache.parseWaypointsFromNote();
        }
        cache.setLogPasswordRequired(response.getBoolean(CACHE_REQ_PASSWORD));

        cache.setDetailedUpdatedNow();
        // save full detailed caches
        DataStore.saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB));
    } catch (final JSONException e) {
        Log.e("OkapiClient.parseCache", e);
    }
    return cache;
}

From source file:cgeo.geocaching.connector.oc.OkapiClient.java

private static void parseCoreCache(final JSONObject response, final Geocache cache) throws JSONException {
    cache.setGeocode(response.getString(CACHE_CODE));
    cache.setName(response.getString(CACHE_NAME));
    // not used: names
    setLocation(cache, response.getString(CACHE_LOCATION));
    cache.setType(getCacheType(response.getString(CACHE_TYPE)));

    final String status = response.getString(CACHE_STATUS);
    cache.setDisabled(status.equalsIgnoreCase(CACHE_STATUS_DISABLED));
    cache.setArchived(status.equalsIgnoreCase(CACHE_STATUS_ARCHIVED));

    cache.setSize(getCacheSize(response));
    cache.setDifficulty((float) response.getDouble(CACHE_DIFFICULTY));
    cache.setTerrain((float) response.getDouble(CACHE_TERRAIN));

    if (!response.isNull(CACHE_IS_FOUND)) {
        cache.setFound(response.getBoolean(CACHE_IS_FOUND));
    }/* w  ww  .  j  a  v a  2s. co m*/
    cache.setHidden(parseDate(response.getString(CACHE_HIDDEN)));
}

From source file:cgeo.geocaching.connector.oc.OkapiClient.java

private static CacheSize getCacheSizeDeprecated(final JSONObject response) {
    if (response.isNull(CACHE_SIZE_DEPRECATED)) {
        return CacheSize.NOT_CHOSEN;
    }/*from   w  w w .  jav  a 2s . co m*/
    double size = 0;
    try {
        size = response.getDouble(CACHE_SIZE_DEPRECATED);
    } catch (final JSONException e) {
        Log.e("OkapiClient.getCacheSize", e);
    }
    switch ((int) Math.round(size)) {
    case 1:
        return CacheSize.MICRO;
    case 2:
        return CacheSize.SMALL;
    case 3:
        return CacheSize.REGULAR;
    case 4:
        return CacheSize.LARGE;
    case 5:
        return CacheSize.VERY_LARGE;
    default:
        break;
    }
    return CacheSize.NOT_CHOSEN;
}

From source file:fr.immotronic.ubikit.pems.enocean.impl.item.data.EEP070904DataImpl.java

public static EEP070904DataImpl constructDataFromRecord(JSONObject lastKnownData) {
    if (lastKnownData == null)
        return new EEP070904DataImpl(Float.MIN_VALUE, -1, Float.MIN_VALUE, null);

    try {/*from  w  ww.j a  va 2  s .c o  m*/
        float relativeHumidity = (float) lastKnownData.getDouble("relativeHumidity");
        int CO2ppm = lastKnownData.getInt("CO2ppm");
        float temperature = (float) lastKnownData.getDouble("temperature");
        Date date = new Date(lastKnownData.getLong("date"));

        return new EEP070904DataImpl(relativeHumidity, CO2ppm, temperature, date);
    } catch (JSONException e) {
        Logger.error(LC.gi(), null,
                "constructDataFromRecord(): An exception while building a sensorData from a JSONObject SHOULD never happen. Check the code !",
                e);
        return new EEP070904DataImpl(Float.MIN_VALUE, -1, Float.MIN_VALUE, null);
    }
}