List of usage examples for org.json JSONObject getDouble
public double getDouble(String key) throws JSONException
From source file:com.kevinquan.android.utils.JSONUtils.java
/** * Retrieve a double stored at the provided key from the provided JSON object * @param obj The JSON object to retrieve from * @param key The key to retrieve/*from w w w . jav a 2 s. c o m*/ * @return the double stored in the key, or the default value if the key doesn't exist */ public static double safeGetDouble(JSONObject obj, String key, double defaultValue) { if (obj == null || TextUtils.isEmpty(key)) return defaultValue; if (obj.has(key)) { try { return obj.getDouble(key); } catch (JSONException e) { Log.w(TAG, "Could not get double from key " + key, e); } } return defaultValue; }
From source file:cgeo.geocaching.connector.gc.GCParser.java
public static SearchResult searchByAddress(final String address, final CacheType cacheType, final boolean showCaptcha, RecaptchaReceiver recaptchaReceiver) { if (StringUtils.isBlank(address)) { Log.e("GCParser.searchByAddress: No address given"); return null; }/*from w w w . j ava 2s . c om*/ try { final JSONObject response = Network.requestJSON("http://www.geocaching.com/api/geocode", new Parameters("q", address)); if (response == null) { return null; } if (!StringUtils.equalsIgnoreCase(response.getString("status"), "success")) { return null; } if (!response.has("data")) { return null; } final JSONObject data = response.getJSONObject("data"); if (data == null) { return null; } return searchByCoords(new Geopoint(data.getDouble("lat"), data.getDouble("lng")), cacheType, showCaptcha, recaptchaReceiver); } catch (final JSONException e) { Log.w("GCParser.searchByAddress", e); } return null; }
From source file:app.com.example.android.sunshine.ForecastFragment.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./*from w w w. jav a2 s. c o m*/ */ private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays) throws JSONException { // These are the names of the JSON objects that need to be extracted. final String OWM_LIST = "list"; final String OWM_WEATHER = "weather"; final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_DATETIME = "dt"; final String OWM_DESCRIPTION = "main"; JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); String[] resultStrs = new String[numDays]; for (int i = 0; i < weatherArray.length(); i++) { // For now, using the format "Day, description, hi/low" String day; String description; String highAndLow; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // The date/time is returned as a long. We need to convert that // into something human-readable, since most people won't read "1400356800" as // "this saturday". long dateTime = dayForecast.getLong(OWM_DATETIME); day = getReadableDateString(dateTime); // description is in a child array called "weather", which is 1 element long. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); // 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); double high = temperatureObject.getDouble(OWM_MAX); double low = temperatureObject.getDouble(OWM_MIN); highAndLow = formatHighLows(high, low); resultStrs[i] = day + " - " + description + " - " + highAndLow; } return resultStrs; }
From source file:com.example.quadros_10084564.sunshine_v2.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./*from ww w. ja v a2 s . co m*/ */ 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); } 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(); } }
From source file:gr.cti.android.experimentation.controller.api.HistoryController.java
@ApiOperation(value = "experiment") @ResponseBody//from w w w. j ava2s . c om @RequestMapping(value = { "/entities/{entity_id}/readings" }, method = RequestMethod.GET) public HistoricDataDTO experimentView(@PathVariable("entity_id") final String entityId, @RequestParam(value = "attribute_id") final String attributeId, @RequestParam(value = "from") final String from, @RequestParam(value = "to") final String to, @RequestParam(value = "all_intervals", required = false, defaultValue = "true") final boolean allIntervals, @RequestParam(value = "rollup", required = false, defaultValue = "") final String rollup, @RequestParam(value = "function", required = false, defaultValue = "avg") final String function) { final HistoricDataDTO historicDataDTO = new HistoricDataDTO(); historicDataDTO.setEntity_id(entityId); historicDataDTO.setAttribute_id(attributeId); historicDataDTO.setFunction(function); historicDataDTO.setRollup(rollup); historicDataDTO.setFrom(from); historicDataDTO.setTo(to); historicDataDTO.setReadings(new ArrayList<>()); final List<TempReading> tempReadings = new ArrayList<>(); long fromLong = parseDateMillis(from); long toLong = parseDateMillis(to); final String[] parts = entityId.split(":"); final String phoneId = parts[parts.length - 1]; LOGGER.info("phoneId: " + phoneId + " from: " + from + " to: " + to); final Set<Result> results = resultRepository.findByDeviceIdAndTimestampBetween(Integer.parseInt(phoneId), fromLong, toLong); final Set<Result> resultsCleanup = new HashSet<>(); for (final Result result : results) { try { final JSONObject readingList = new JSONObject(result.getMessage()); final Iterator keys = readingList.keys(); while (keys.hasNext()) { final String key = (String) keys.next(); if (key.contains(attributeId)) { tempReadings.add(new TempReading(result.getTimestamp(), readingList.getDouble(key))); } } } catch (JSONException e) { resultsCleanup.add(result); } catch (Exception e) { LOGGER.error(e, e); } } resultRepository.delete(resultsCleanup); List<TempReading> rolledUpTempReadings = new ArrayList<>(); if ("".equals(rollup)) { rolledUpTempReadings = tempReadings; } else { final Map<Long, SummaryStatistics> dataMap = new HashMap<>(); for (final TempReading tempReading : tempReadings) { Long millis = null; //TODO: make rollup understand the first integer part if (rollup.endsWith("m")) { millis = new DateTime(tempReading.getTimestamp()).withMillisOfSecond(0).withSecondOfMinute(0) .getMillis(); } else if (rollup.endsWith("h")) { millis = new DateTime(tempReading.getTimestamp()).withMillisOfSecond(0).withSecondOfMinute(0) .withMinuteOfHour(0).getMillis(); } else if (rollup.endsWith("d")) { millis = new DateTime(tempReading.getTimestamp()).withMillisOfDay(0).getMillis(); } if (millis != null) { if (!dataMap.containsKey(millis)) { dataMap.put(millis, new SummaryStatistics()); } dataMap.get(millis).addValue(tempReading.getValue()); } } final TreeSet<Long> treeSet = new TreeSet<>(); treeSet.addAll(dataMap.keySet()); if (allIntervals) { fillMissingIntervals(treeSet, rollup, toLong); } for (final Long millis : treeSet) { if (dataMap.containsKey(millis)) { rolledUpTempReadings.add(parse(millis, function, dataMap.get(millis))); } else { rolledUpTempReadings.add(new TempReading(millis, 0)); } } } for (final TempReading tempReading : rolledUpTempReadings) { List<Object> list = new ArrayList<>(); list.add(df.format(tempReading.getTimestamp())); list.add(tempReading.getValue()); historicDataDTO.getReadings().add(list); } return historicDataDTO; }
From source file:com.jennifer.ui.chart.widget.LegendWidget.java
@Override public Object draw() { double x = 0, y = 0, total_width = 0, total_height = 0, max_width = 0, max_height = 0; for (int i = 0, len = brush.length(); i < len; i++) { int index = brush.getInt(i); JSONObject brushObject = chart.brush(index); JSONArray arr = getLegendIcon(brushObject); for (int k = 0, kLen = arr.length(); k < kLen; k++) { JSONObject obj = arr.getJSONObject(k); double w = obj.getDouble("width"); double h = obj.getDouble("height"); Transform icon = (Transform) obj.get("icon"); //root.append(icon); icon.translate(x, y);/*from www . j av a 2 s . c om*/ if ("bottom".equals(position) || "top".equals(position)) { x += w; total_width += w; if (max_height < h) { max_height = h; } } else { y += h; total_height += h; if (max_width < w) { max_width = w; } } } } if ("bottom".equals(position) || "top".equals(position)) { y = ("bottom".equals(position)) ? chart.area("y2") + chart.padding("bottom") - max_height : chart.area("y") - chart.padding("top"); if ("start".equals(align)) { x = chart.area("x"); } else if ("center".equals(align)) { x = chart.area("x") + (chart.area("width") / 2.0 - total_width / 2.0); } else if ("end".equals(align)) { x = chart.area("x2") - total_width; } } else { x = ("left".equals(position)) ? chart.area("x") - max_width : chart.area("x2") + 20; if ("start".equals(align)) { y = chart.area("y"); } else if ("center".equals(align)) { y = chart.area("y") + (chart.area("height") / 2.0 - total_height / 2.0); } else if ("end".equals(align)) { y = chart.area("y2") - total_height; } } root.translate(x + 0.5, y + 0.5); return new JSONObject().put("root", root); }
From source file:jessmchung.groupon.parsers.PriceParser.java
@Override public Price parse(JSONObject json) throws JSONException { Price obj = new Price(); if (json.has("currencyCode")) obj.setCurrencyCode(json.getString("currencyCode")); if (json.has("amount")) obj.setAmount(json.getDouble("amount")); if (json.has("formattedAmount")) obj.setFormattedAmount(json.getString("formattedAmount")); return obj;/*from ww w . j a va2s . c o m*/ }
From source file:fr.pasteque.pos.customers.DiscountProfile.java
public DiscountProfile(JSONObject o) { if (!o.isNull("id")) { this.id = o.getInt("id"); }// w w w . jav a2 s . c om this.name = o.getString("label"); this.rate = o.getDouble("rate"); }
From source file:com.clearcenter.mobile_demo.mdStatusActivity.java
public void updateData() { JSONObject json_data; String projection[] = new String[] { mdDeviceSamples.DATA }; Cursor cursor = getContentResolver().query(mdDeviceSamples.CONTENT_URI, projection, mdDeviceSamples.NICKNAME + " = ?", new String[] { account_nickname }, null); int rows = 0; try {/*w w w. ja v a 2 s . c o m*/ rows = cursor.getCount(); } catch (NullPointerException e) { } Log.d(TAG, "Matches: " + rows); if (rows == 0) { Log.d(TAG, "No rows match for nickname: " + account_nickname); cursor.close(); return; } cursor.moveToLast(); String data = cursor.getString(cursor.getColumnIndex(mdDeviceSamples.DATA)); try { json_data = new JSONObject(data); if (json_data.has("hostname")) hostname_textview.setText("Hostname: " + json_data.getString("hostname")); if (json_data.has("name") && json_data.has("release")) { final String release = json_data.getString("name") + " " + json_data.getString("release"); release_textview.setText("Release: " + release); } if (json_data.has("time_locale")) { time_textview.setText("Clock: " + json_data.getString("time_locale")); } if (rows >= 2) { bw_graphview.reset(); loadavg_graphview.reset(); mem_graphview.reset(); if (rows <= samples) cursor.moveToFirst(); else cursor.move(-samples); long unix_time = 0; double bw_up = 0.0; double bw_down = 0.0; do { data = cursor.getString(cursor.getColumnIndex(mdDeviceSamples.DATA)); final List<JSONObject> samples = sortedSamplesList(data); ListIterator<JSONObject> li = samples.listIterator(); while (li.hasNext()) { json_data = li.next(); if (unix_time == 0) { bw_up = json_data.getDouble("bandwidth_up"); bw_down = json_data.getDouble("bandwidth_down"); unix_time = Long.valueOf(json_data.getString("time")); continue; } long diff = Long.valueOf(json_data.getString("time")) - unix_time; double rate_up = (json_data.getDouble("bandwidth_up") - bw_up) / diff; double rate_down = (json_data.getDouble("bandwidth_down") - bw_down) / diff; if (rate_up < 0.0) rate_up = 0.0; if (rate_down < 0.0) rate_down = 0.0; bw_graphview.addSample(bw_graph_up, unix_time, (float) rate_up); bw_graphview.addSample(bw_graph_down, unix_time, (float) rate_down); // Log.d(TAG, "time: " + diff + // ", rate_up: " + rate_up + ", rate_down: " + rate_down); bw_up = json_data.getDouble("bandwidth_up"); bw_down = json_data.getDouble("bandwidth_down"); loadavg_graphview.addSample(loadavg_graph_5min, unix_time, (float) json_data.getDouble("loadavg_5min")); loadavg_graphview.addSample(loadavg_graph_15min, unix_time, (float) json_data.getDouble("loadavg_15min")); mem_graphview.addSample(mem_graph_active, unix_time, (float) json_data.getDouble("mem_active")); mem_graphview.addSample(mem_graph_swap, unix_time, (float) json_data.getDouble("mem_swap_used")); unix_time = Long.valueOf(json_data.getString("time")); } } while (cursor.moveToNext()); bw_graphview.update(); loadavg_graphview.update(); mem_graphview.update(); } } catch (JSONException e) { Log.e(TAG, "JSONException", e); } cursor.close(); }
From source file:tracerouteip.FXMLDocumentController.java
@FXML private void handleButtonTrace(ActionEvent event) { String str = tf_dest.getText(); if (!str.isEmpty())//Saisie destiantion non vide {/*w ww.ja v a2s . co m*/ if (str.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"))//Destination est une ipV4 { System.out.println("Destination IPV4 OK"); } else //On suppose que destination est une URL { System.out.println("Destination URL"); try { adrDest = InetAddress.getByName(str); str = adrDest.getHostAddress(); System.out.println("IP destination : " + str); } catch (UnknownHostException ex) { System.out.println("Erreur getByName"); } } //try { //https://code.google.com/p/org-json-java/downloads/list try { URI uri; //uri = new URI("http://freegeoip.net/json/"+str); uri = new URI("http://ip-api.com/json/" + str); System.out.println("URI : " + uri.toString()); URL url = uri.toURL(); InputStream inputStream = url.openStream(); JSONTokener tokener = new JSONTokener(inputStream); JSONObject root = new JSONObject(tokener); //String rootJson = root.toString(); //System.out.println("rootJson : "+rootJson); /*double lat = root.getDouble("latitude"); double lng = root.getDouble("longitude");*/ double lat = root.getDouble("lat"); double lng = root.getDouble("lon"); System.out.println("Latitude : " + lat + "\nLongitude : " + lng); } catch (URISyntaxException ex) { Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex); } catch (MalformedURLException ex) { Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex); } catch (JSONException ex) { Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex); } } else { System.out.println("Destination VIDE"); } }