List of usage examples for org.json JSONObject getDouble
public double getDouble(String key) throws JSONException
From source file:com.iyedb.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 w w . j a v a 2s. co m*/ * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us. */ private void getWeatherDataFromJson(String forecastJsonStr, int numDays, String locationSetting) throws JSONException { // 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"; final String OWM_COORD_LAT = "lat"; final String OWM_COORD_LONG = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_DATETIME = "dt"; 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"; 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 coordJSON = cityJson.getJSONObject(OWM_COORD); double cityLatitude = coordJSON.getLong(OWM_COORD_LAT); double cityLongitude = coordJSON.getLong(OWM_COORD_LONG); Log.v(LOG_TAG, cityName + ", with coord: " + cityLatitude + " " + cityLongitude); // Insert the location into the database. long locationID = insertLocationInDatabase(locationSetting, cityName, cityLatitude, cityLongitude); // Get and insert the new weather information into the database Vector<ContentValues> cvVector = new Vector<ContentValues>(weatherArray.length()); 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); // 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". dateTime = dayForecast.getLong(OWM_DATETIME); 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_DATETEXT, WeatherContract.getDbDateString(new Date(dateTime * 1000L))); 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); } if (cvVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cvVector.size()]; cvVector.toArray(cvArray); int rowsInserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray); Log.v(LOG_TAG, "inserted " + rowsInserted + " rows of weather data"); // Use a DEBUG variable to gate whether or not you do this, so you can easily // turn it on and off, and so that it's easy to see what you can rip out if // you ever want to remove it. if (DEBUG) { Cursor weatherCursor = mContext.getContentResolver().query(WeatherEntry.CONTENT_URI, null, null, null, null); if (weatherCursor.moveToFirst()) { Log.v(LOG_TAG, "Query succeeded! **********"); } else { Log.v(LOG_TAG, "Query failed! :( **********"); } } } }
From source file:org.marietjedroid.connect.MarietjeClient.java
/** * locks when waiting for a track/*from w w w . j a v a2 s . c o m*/ * * @return the now playing track * @throws MarietjeException */ public MarietjePlaying getPlaying() throws MarietjeException { if (channel.getException() != null) throw channel.getException(); MarietjePlaying nowPlaying = null; try { if (!followingPlaying || this.channel.getNowPlaying() == null) { this.followPlaying(); this.playingRetrieved.acquire(); } JSONObject np = this.channel.getNowPlaying(); JSONObject media = np.getJSONObject("media"); double servertime = np.getDouble("serverTime"); double endtime = np.getDouble("endTime"); String byKey = np.getString("byKey"); nowPlaying = new MarietjePlaying(byKey, servertime, endtime, media); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { throw new MarietjeException("JSON error"); } return nowPlaying; }
From source file:ru.orangesoftware.financisto2.rates.OpenExchangeRatesDownloader.java
private void updateRate(JSONObject json, ExchangeRate exchangeRate, Currency fromCurrency, Currency toCurrency) throws JSONException { JSONObject rates = json.getJSONObject("rates"); double usdFrom = rates.getDouble(fromCurrency.name); double usdTo = rates.getDouble(toCurrency.name); exchangeRate.rate = usdTo * (1 / usdFrom); exchangeRate.date = 1000 * json.optLong("timestamp", System.currentTimeMillis()); }
From source file:org.akvo.flow.api.parser.json.SurveyedLocaleParser.java
public SurveyedLocale parseSurveyedLocale(JSONObject jSurveyedLocale) throws JSONException { String id = jSurveyedLocale.getString(Attrs.ID); long lastModified = jSurveyedLocale.getLong(Attrs.LAST_MODIFIED); long surveyGroupId = jSurveyedLocale.getLong(Attrs.SURVEY_GROUP_ID); Double latitude = jSurveyedLocale.has(Attrs.LATITUDE) && !jSurveyedLocale.isNull(Attrs.LATITUDE) ? jSurveyedLocale.getDouble(Attrs.LATITUDE) : null;/*from www . j a va 2 s.c o m*/ Double longitude = jSurveyedLocale.has(Attrs.LONGITUDE) && !jSurveyedLocale.isNull(Attrs.LONGITUDE) ? jSurveyedLocale.getDouble(Attrs.LONGITUDE) : null; String name = jSurveyedLocale.has(Attrs.NAME) && !jSurveyedLocale.isNull(Attrs.NAME) ? jSurveyedLocale.getString(Attrs.NAME) : null; JSONArray jSurveyInstances = jSurveyedLocale.getJSONArray(Attrs.SURVEY_INSTANCES); List<SurveyInstance> surveyInstances = new SurveyInstanceParser().parseList(jSurveyInstances); SurveyedLocale surveyedLocale = new SurveyedLocale(id, name, lastModified, surveyGroupId, latitude, longitude); surveyedLocale.setSurveyInstances(surveyInstances); return surveyedLocale; }
From source file:fr.cvlaminck.nominatim.json.PlaceJsonParser.java
@Override protected Place doParseFromJson(JSONObject json) throws JSONException, NominatimAPIResponseException { Place p = new Place(); p.setPlaceId(json.getLong(PLACE_ID)); p.setOsmId(json.getLong(PLACE_OSM_ID)); p.setType(PlaceType.typeForName(json.getString(PLACE_TYPE))); p.setOsmType(OsmType.typeForName(json.getString(PLACE_OSM_TYPE))); if (json.has(PLACE_CATEGORY)) { p.setCategory(PlaceCategory.categoryForName(json.getString(PLACE_CATEGORY))); }// www . ja v a2 s . c o m if (json.has(PLACE_CLASS)) { p.setCategory(PlaceCategory.categoryForName(json.getString(PLACE_CLASS))); } p.setType(PlaceType.typeForName(json.getString(PLACE_TYPE))); if (json.has(PLACE_ICON)) { p.setIcon(json.getString(PLACE_ICON)); } p.setDisplayName(json.getString(PLACE_DISPLAY_NAME)); p.setLongitude(json.getDouble(PLACE_LONGITUDE)); p.setLatitude(json.getDouble(PLACE_LATITUDE)); if (json.has(PLACE_ADDRESS)) { p.setAddress(getAddressParser().parse(json.getJSONObject(PLACE_ADDRESS))); } //FIXME bounding box if (json.has(PLACE_RANK)) { p.setPlaceRank(json.getInt(PLACE_RANK)); } p.setImportance(json.getDouble(PLACE_IMPORTANCE)); p.setLicence(json.getString(PLACE_LICENCE)); return p; }
From source file:es.alrocar.map.vector.provider.driver.wikipedia.WikipediaDriver.java
@Override public Point processResult(JSONObject object) { String title = null, url = null, distance = null; double lat = 0, lon = 0; try {/*w w w . j ava2 s .c o m*/ lat = object.getDouble("lat"); } catch (JSONException e) { // TODO Auto-generated catch block // e.printStackTrace(); } try { lon = object.getDouble("lng"); } catch (JSONException e) { // TODO Auto-generated catch block // e.printStackTrace(); } try { title = object.getString("title"); } catch (JSONException e) { // TODO Auto-generated catch block // e.printStackTrace(); } try { url = object.getString("url"); } catch (JSONException e) { // TODO Auto-generated catch block // e.printStackTrace(); } try { distance = object.getString("distance"); } catch (JSONException e) { // TODO Auto-generated catch block // e.printStackTrace(); } if (lat == 0 || lon == 0) return null; WikipediaPoint p = new WikipediaPoint(); p.setTitle(title); p.setUrl(url); p.setDistance(distance); p.setX(lon); p.setY(lat); return p; }
From source file:fr.bde_eseo.eseomega.lacommande.model.LacmdIngredient.java
public LacmdIngredient(JSONObject obj) throws JSONException { super(obj.getString("name"), obj.getString("idstr"), 0, 0, obj.getDouble("priceuni"), ID_CAT_INGREDIENT); this.stock = obj.getInt("stock"); }
From source file:com.soomla.store.domain.GoogleMarketItem.java
/** Constructor * * Generates an instance of {@link GoogleMarketItem} from a JSONObject. * @param jsonObject is a JSONObject representation of the wanted {@link GoogleMarketItem}. * @throws JSONException/*from ww w.j a v a 2 s . co m*/ */ public GoogleMarketItem(JSONObject jsonObject) throws JSONException { if (jsonObject.has(JSONConsts.MARKETITEM_MANAGED)) { this.mManaged = Managed.values()[jsonObject.getInt(JSONConsts.MARKETITEM_MANAGED)]; } else { this.mManaged = Managed.UNMANAGED; } if (jsonObject.has(JSONConsts.MARKETITEM_ANDROID_ID)) { this.mProductId = jsonObject.getString(JSONConsts.MARKETITEM_ANDROID_ID); } else { this.mProductId = jsonObject.getString(JSONConsts.MARKETITEM_PRODUCT_ID); } this.mPrice = jsonObject.getDouble(JSONConsts.MARKETITEM_PRICE); }
From source file:com.home883.ali.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 ww . j a v a 2s . c o 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); } // add to database if (cVVector.size() > 0) { // Student: call bulkInsert to add the weatherEntries to the database here ContentValues[] cVArray = cVVector.toArray(new ContentValues[cVVector.size()]); 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(cVVector); return resultStrs; } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } return null; }
From source file:fr.cph.stock.android.entity.EntityBuilder.java
private void buildPortfolio() throws JSONException { portfolio = new Portfolio(); JSONObject jsonPortfolio = json.getJSONObject("portfolio"); double totalValueStr = jsonPortfolio.getDouble("totalValue"); portfolio.setTotalValue(formatCurrencyZero.format(totalValueStr)); double totalGain = jsonPortfolio.getDouble("totalGain"); portfolio.setTotalGain(formatCurrencyZero.format(totalGain)); double totalPlusMinusValue = jsonPortfolio.getDouble("totalPlusMinusValue"); portfolio.setTotalPlusMinusValue(// w ww.ja v a 2 s.c o m totalPlusMinusValue > 0 ? "+" + formatLocaleOne.format(totalPlusMinusValue) + "%" : formatLocaleOne.format(totalPlusMinusValue) + "%"); portfolio.setUp(totalGain > 0 ? true : false); double liquidity = jsonPortfolio.getDouble("liquidity"); portfolio.setLiquidity(formatCurrencyZero.format(liquidity)); double yieldYear = jsonPortfolio.getDouble("yieldYear"); portfolio.setYieldYear(formatCurrencyZero.format(yieldYear)); double yieldYearPerc = jsonPortfolio.getDouble("yieldYearPerc"); portfolio.setYieldYearPerc(formatLocaleOne.format(yieldYearPerc) + "%"); JSONObject lastUpdateJSON = jsonPortfolio.getJSONObject("lastUpdate"); portfolio.setLastUpdate(extractDate(lastUpdateJSON, user.getDatePattern())); JSONArray arrayEquities = jsonPortfolio.getJSONArray("equities"); portfolio.setEquities(buildEquities(arrayEquities)); JSONArray arrayShareValues = jsonPortfolio.getJSONArray("shareValues"); portfolio.setShareValues(buildShareValues(arrayShareValues)); JSONArray arrayAccounts = jsonPortfolio.getJSONArray("accounts"); portfolio.setAccounts(buildAccounts(arrayAccounts)); JSONObject performance = jsonPortfolio.getJSONObject("performance"); portfolio.setGainPerformance(formatCurrencyOne.format(performance.getDouble("gain"))); portfolio.setPerformancePerformance(formatLocaleOne.format(performance.getDouble("performance")) + "%"); portfolio.setYieldPerformance(formatCurrencyOne.format(performance.getDouble("yield"))); portfolio.setTaxesPerformace(formatCurrencyOne.format(performance.getDouble("taxes"))); portfolio.setChartColors(jsonPortfolio.getString("chartShareValueColors")); portfolio.setChartData(jsonPortfolio.getString("chartShareValueData")); portfolio.setChartDate(jsonPortfolio.getString("chartShareValueDate")); portfolio.setChartDraw(jsonPortfolio.getString("chartShareValueDraw")); portfolio.setChartSectorData(jsonPortfolio.getString("chartSectorData")); portfolio.setChartSectorTitle(jsonPortfolio.getString("chartSectorTitle")); portfolio.setChartSectorDraw(jsonPortfolio.getString("chartSectorDraw")); portfolio.setChartSectorCompanies(jsonPortfolio.getString("chartSectorCompanies")); portfolio.setChartCapCompanies(jsonPortfolio.getString("chartCapCompanies")); portfolio.setChartCapData(jsonPortfolio.getString("chartCapData")); portfolio.setChartCapDraw(jsonPortfolio.getString("chartCapDraw")); portfolio.setChartCapTitle(jsonPortfolio.getString("chartCapTitle")); double totalVariation = jsonPortfolio.getDouble("totalVariation"); if (totalVariation >= 0) { portfolio.setTodayUp(true); portfolio.setTotalVariation("+" + formatLocaleTwo.format(totalVariation) + "%"); } else { portfolio.setTodayUp(false); portfolio.setTotalVariation(formatLocaleTwo.format(totalVariation) + "%"); } }