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:com.github.mhendred.face4j.model.Point.java

static Point fromJson(JSONObject jObj) throws JSONException {
    if (jObj != null) {
        final Point p = new Point();

        p.x = (float) jObj.getDouble("x");
        p.y = (float) jObj.getDouble("y");

        return p;
    }/*from   w w  w .  j  av a  2  s. c  om*/

    return null;
}

From source file:com.mobile.system.db.abatis.AbatisService.java

/**
 * /*from   w  ww. j  a va2 s  . c o m*/
 * @param jsonStr
 *            JSON String
 * @param beanClass
 *            Bean class
 * @param basePackage
 *            Base package name which includes all Bean classes
 * @return Object Bean
 * @throws Exception
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public Object parse(String jsonStr, Class beanClass, String basePackage) throws Exception {
    Object obj = null;
    JSONObject jsonObj = new JSONObject(jsonStr);
    // Check bean object
    if (beanClass == null) {
        Log.d(TAG, "Bean class is null");
        return null;
    }
    // Read Class member fields
    Field[] props = beanClass.getDeclaredFields();
    if (props == null || props.length == 0) {
        Log.d(TAG, "Class" + beanClass.getName() + " has no fields");
        return null;
    }
    // Create instance of this Bean class
    obj = beanClass.newInstance();
    // Set value of each member variable of this object
    for (int i = 0; i < props.length; i++) {
        String fieldName = props[i].getName();
        // Skip public and static fields
        if (props[i].getModifiers() == (Modifier.PUBLIC | Modifier.STATIC)) {
            continue;
        }
        // Date Type of Field
        Class type = props[i].getType();
        String typeName = type.getName();
        // Check for Custom type
        if (typeName.equals("int")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getInt(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("long")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getLong(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("java.lang.String")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getString(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("double")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getDouble(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("java.util.Date")) { // modify

            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);

            String dateString = jsonObj.getString(fieldName);
            dateString = dateString.replace(" KST", "");
            SimpleDateFormat genderFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy", Locale.KOREA);
            // Set value
            try {
                Date afterDate = genderFormat.parse(dateString);
                m.invoke(obj, afterDate);
            } catch (Exception e) {
                Log.d(TAG, e.getMessage());
            }
        } else if (type.getName().equals(List.class.getName())
                || type.getName().equals(ArrayList.class.getName())) {
            // Find out the Generic
            String generic = props[i].getGenericType().toString();
            if (generic.indexOf("<") != -1) {
                String genericType = generic.substring(generic.lastIndexOf("<") + 1, generic.lastIndexOf(">"));
                if (genericType != null) {
                    JSONArray array = null;
                    try {
                        array = jsonObj.getJSONArray(fieldName);
                    } catch (Exception ex) {
                        Log.d(TAG, ex.getMessage());
                        array = null;
                    }
                    if (array == null) {
                        continue;
                    }
                    ArrayList arrayList = new ArrayList();
                    for (int j = 0; j < array.length(); j++) {
                        arrayList.add(parse(array.getJSONObject(j).toString(), Class.forName(genericType),
                                basePackage));
                    }
                    // Set value
                    Class[] parms = { type };
                    Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
                    m.setAccessible(true);
                    m.invoke(obj, arrayList);
                }
            } else {
                // No generic defined
                generic = null;
            }
        } else if (typeName.startsWith(basePackage)) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                JSONObject customObj = jsonObj.getJSONObject(fieldName);
                if (customObj != null) {
                    m.invoke(obj, parse(customObj.toString(), type, basePackage));
                }
            } catch (JSONException ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else {
            // Skip
            Log.d(TAG, "Field " + fieldName + "#" + typeName + " is skip");
        }
    }
    return obj;
}

From source file:com.nginious.http.serialize.JsonSerializerTestCase.java

public void testJsonSerializer() throws Exception {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
    SerializableBean bean = new SerializableBean();
    bean.setBooleanValue(true);// w  ww  . j  a  v a2 s.c  om
    bean.setDoubleValue(0.451);
    bean.setFloatValue(1.34f);
    bean.setIntValue(3400100);
    bean.setLongValue(3400100200L);
    bean.setShortValue((short) 32767);
    bean.setStringValue("String");
    bean.setDateValue(format.parse("2011-08-24T08:50:23+0200"));
    Date calDate = format.parse("2011-08-24T08:52:23+0200");
    Calendar cal = Calendar.getInstance();
    cal.setTime(calDate);
    bean.setCalendarValue(cal);
    bean.setObjectValue(TimeZone.getDefault());

    InBean inBean = new InBean();
    inBean.setFirst(true);
    inBean.setSecond(0.567d);
    inBean.setThird(0.342f);
    inBean.setFourth(100);
    inBean.setFifth(3400200100L);
    inBean.setSixth((short) 32767);
    inBean.setSeventh("String");
    inBean.setEight(format.parse("2011-08-25T08:50:23+0200"));
    cal = Calendar.getInstance();
    calDate = format.parse("2011-08-25T08:52:23+0200");
    cal.setTime(calDate);
    inBean.setNinth(cal);
    bean.setBeanValue(inBean);

    List<InBean> beanList = new ArrayList<InBean>();
    beanList.add(inBean);
    beanList.add(inBean);
    bean.setBeanListValue(beanList);

    List<String> stringList = new ArrayList<String>();
    stringList.add("One");
    stringList.add("Two");
    stringList.add("Three");
    bean.setStringListValue(stringList);

    ApplicationClassLoader classLoader = new ApplicationClassLoader(
            Thread.currentThread().getContextClassLoader());
    SerializerFactoryImpl serializerFactory = new SerializerFactoryImpl(classLoader);
    Serializer<SerializableBean> serializer = serializerFactory.createSerializer(SerializableBean.class,
            "application/json");
    assertEquals("application/json", serializer.getMimeType());

    StringWriter strWriter = new StringWriter();
    PrintWriter writer = new PrintWriter(strWriter);

    serializer.serialize(writer, bean);
    writer.flush();
    JSONObject json = new JSONObject(strWriter.toString());
    assertNotNull(json);
    assertTrue(json.has("serializableBean"));
    json = json.getJSONObject("serializableBean");

    assertEquals(true, json.getBoolean("booleanValue"));
    assertEquals(0.451, json.getDouble("doubleValue"));
    assertEquals(1.34f, (float) json.getDouble("floatValue"));
    assertEquals(3400100, json.getInt("intValue"));
    assertEquals(3400100200L, json.getLong("longValue"));
    assertEquals(32767, (short) json.getInt("shortValue"));
    assertEquals("String", json.getString("stringValue"));
    assertEquals("2011-08-24T08:50:23+02:00", json.getString("dateValue"));
    assertEquals("2011-08-24T08:52:23+02:00", json.getString("calendarValue"));
    assertEquals(TimeZone.getDefault().toString(), json.getString("objectValue"));

    assertTrue(json.has("beanValue"));
    JSONObject inBeanJson = json.getJSONObject("beanValue");
    assertTrue(inBeanJson.has("inBean"));
    inBeanJson = inBeanJson.getJSONObject("inBean");
    assertEquals(true, inBeanJson.getBoolean("first"));
    assertEquals(0.567, inBeanJson.getDouble("second"));
    assertEquals(0.342f, (float) inBeanJson.getDouble("third"));
    assertEquals(100, inBeanJson.getInt("fourth"));
    assertEquals(3400200100L, inBeanJson.getLong("fifth"));
    assertEquals(32767, (short) inBeanJson.getInt("sixth"));
    assertEquals("String", inBeanJson.getString("seventh"));
    assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight"));
    assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth"));

    assertTrue(json.has("stringListValue"));
    JSONArray stringListJson = json.getJSONArray("stringListValue");
    assertEquals("One", stringListJson.get(0));
    assertEquals("Two", stringListJson.get(1));
    assertEquals("Three", stringListJson.get(2));

    assertTrue(json.has("beanListValue"));
    JSONArray beanListJson = json.getJSONArray("beanListValue");

    inBeanJson = beanListJson.getJSONObject(0);
    assertTrue(inBeanJson.has("inBean"));
    inBeanJson = inBeanJson.getJSONObject("inBean");
    assertEquals(true, inBeanJson.getBoolean("first"));
    assertEquals(0.567, inBeanJson.getDouble("second"));
    assertEquals(0.342f, (float) inBeanJson.getDouble("third"));
    assertEquals(100, inBeanJson.getInt("fourth"));
    assertEquals(3400200100L, inBeanJson.getLong("fifth"));
    assertEquals(32767, (short) inBeanJson.getInt("sixth"));
    assertEquals("String", inBeanJson.getString("seventh"));
    assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight"));
    assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth"));

    inBeanJson = beanListJson.getJSONObject(1);
    assertTrue(inBeanJson.has("inBean"));
    inBeanJson = inBeanJson.getJSONObject("inBean");
    assertEquals(true, inBeanJson.getBoolean("first"));
    assertEquals(0.567, inBeanJson.getDouble("second"));
    assertEquals(0.342f, (float) inBeanJson.getDouble("third"));
    assertEquals(100, inBeanJson.getInt("fourth"));
    assertEquals(3400200100L, inBeanJson.getLong("fifth"));
    assertEquals(32767, (short) inBeanJson.getInt("sixth"));
    assertEquals("String", inBeanJson.getString("seventh"));
    assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight"));
    assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth"));
}

From source file:com.nginious.http.serialize.JsonSerializerTestCase.java

public void testNamedJsonSerializer() throws Exception {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
    NamedBean bean = new NamedBean();
    bean.setBooleanValue(true);/*from  ww w. j  a  v a 2 s  .c  om*/
    bean.setDoubleValue(0.451);
    bean.setFloatValue(1.34f);
    bean.setIntValue(3400100);
    bean.setLongValue(3400100200L);
    bean.setShortValue((short) 32767);
    bean.setStringValue("String");
    bean.setDateValue(format.parse("2011-08-24T08:50:23+0200"));
    Date calDate = format.parse("2011-08-24T08:52:23+0200");
    Calendar cal = Calendar.getInstance();
    cal.setTime(calDate);
    bean.setCalendarValue(cal);
    bean.setObjectValue(TimeZone.getDefault());

    InBean inBean = new InBean();
    inBean.setFirst(true);
    inBean.setSecond(0.567d);
    inBean.setThird(0.342f);
    inBean.setFourth(100);
    inBean.setFifth(3400200100L);
    inBean.setSixth((short) 32767);
    inBean.setSeventh("String");
    inBean.setEight(format.parse("2011-08-25T08:50:23+0200"));
    cal = Calendar.getInstance();
    calDate = format.parse("2011-08-25T08:52:23+0200");
    cal.setTime(calDate);
    inBean.setNinth(cal);
    bean.setBeanValue(inBean);

    List<InBean> beanList = new ArrayList<InBean>();
    beanList.add(inBean);
    beanList.add(inBean);
    bean.setBeanListValue(beanList);

    List<String> stringList = new ArrayList<String>();
    stringList.add("One");
    stringList.add("Two");
    stringList.add("Three");
    bean.setStringListValue(stringList);

    ApplicationClassLoader classLoader = new ApplicationClassLoader(
            Thread.currentThread().getContextClassLoader());
    SerializerFactoryImpl serializerFactory = new SerializerFactoryImpl(classLoader);
    Serializer<NamedBean> serializer = serializerFactory.createSerializer(NamedBean.class, "application/json");
    assertEquals("application/json", serializer.getMimeType());

    StringWriter strWriter = new StringWriter();
    PrintWriter writer = new PrintWriter(strWriter);

    serializer.serialize(writer, bean);
    writer.flush();
    JSONObject json = new JSONObject(strWriter.toString());
    assertNotNull(json);
    assertTrue(json.has("testNamedBean"));
    json = json.getJSONObject("testNamedBean");

    assertEquals(true, json.getBoolean("testBooleanValue"));
    assertEquals(0.451, json.getDouble("testDoubleValue"));
    assertEquals(1.34f, (float) json.getDouble("testFloatValue"));
    assertEquals(3400100, json.getInt("testIntValue"));
    assertEquals(3400100200L, json.getLong("testLongValue"));
    assertEquals(32767, (short) json.getInt("testShortValue"));
    assertEquals("String", json.getString("testStringValue"));
    assertEquals("2011-08-24T08:50:23+02:00", json.getString("testDateValue"));
    assertEquals("2011-08-24T08:52:23+02:00", json.getString("testCalendarValue"));
    assertEquals(TimeZone.getDefault().toString(), json.getString("testObjectValue"));

    assertTrue(json.has("testBeanValue"));
    JSONObject inBeanJson = json.getJSONObject("testBeanValue");
    assertTrue(inBeanJson.has("inBean"));
    inBeanJson = inBeanJson.getJSONObject("inBean");
    assertEquals(true, inBeanJson.getBoolean("first"));
    assertEquals(0.567, inBeanJson.getDouble("second"));
    assertEquals(0.342f, (float) inBeanJson.getDouble("third"));
    assertEquals(100, inBeanJson.getInt("fourth"));
    assertEquals(3400200100L, inBeanJson.getLong("fifth"));
    assertEquals(32767, (short) inBeanJson.getInt("sixth"));
    assertEquals("String", inBeanJson.getString("seventh"));
    assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight"));
    assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth"));

    assertTrue(json.has("testStringListValue"));
    JSONArray stringListJson = json.getJSONArray("testStringListValue");
    assertEquals("One", stringListJson.get(0));
    assertEquals("Two", stringListJson.get(1));
    assertEquals("Three", stringListJson.get(2));

    assertTrue(json.has("testBeanListValue"));
    JSONArray beanListJson = json.getJSONArray("testBeanListValue");

    inBeanJson = beanListJson.getJSONObject(0);
    assertTrue(inBeanJson.has("inBean"));
    inBeanJson = inBeanJson.getJSONObject("inBean");
    assertEquals(true, inBeanJson.getBoolean("first"));
    assertEquals(0.567, inBeanJson.getDouble("second"));
    assertEquals(0.342f, (float) inBeanJson.getDouble("third"));
    assertEquals(100, inBeanJson.getInt("fourth"));
    assertEquals(3400200100L, inBeanJson.getLong("fifth"));
    assertEquals(32767, (short) inBeanJson.getInt("sixth"));
    assertEquals("String", inBeanJson.getString("seventh"));
    assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight"));
    assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth"));

    inBeanJson = beanListJson.getJSONObject(1);
    assertTrue(inBeanJson.has("inBean"));
    inBeanJson = inBeanJson.getJSONObject("inBean");
    assertEquals(true, inBeanJson.getBoolean("first"));
    assertEquals(0.567, inBeanJson.getDouble("second"));
    assertEquals(0.342f, (float) inBeanJson.getDouble("third"));
    assertEquals(100, inBeanJson.getInt("fourth"));
    assertEquals(3400200100L, inBeanJson.getLong("fifth"));
    assertEquals(32767, (short) inBeanJson.getInt("sixth"));
    assertEquals("String", inBeanJson.getString("seventh"));
    assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight"));
    assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth"));
}

From source file:com.nginious.http.serialize.JsonSerializerTestCase.java

public void testEmptyJsonSerializer() throws Exception {
    SerializableBean bean = new SerializableBean();
    ApplicationClassLoader classLoader = new ApplicationClassLoader(
            Thread.currentThread().getContextClassLoader());
    SerializerFactoryImpl serializerFactory = new SerializerFactoryImpl(classLoader);
    Serializer<SerializableBean> serializer = serializerFactory.createSerializer(SerializableBean.class,
            "application/json");
    assertEquals("application/json", serializer.getMimeType());

    StringWriter strWriter = new StringWriter();
    PrintWriter writer = new PrintWriter(strWriter);
    serializer.serialize(writer, bean);/*w w w.jav  a2 s  .c om*/
    writer.flush();
    JSONObject json = new JSONObject(strWriter.toString());
    assertNotNull(json);
    assertTrue(json.has("serializableBean"));
    json = json.getJSONObject("serializableBean");

    assertEquals(false, json.getBoolean("booleanValue"));
    assertEquals(0.0d, json.getDouble("doubleValue"));
    assertEquals(0.0f, (float) json.getDouble("floatValue"));
    assertEquals(0, json.getInt("intValue"));
    assertEquals(0L, json.getLong("longValue"));
    assertEquals(0, (short) json.getInt("shortValue"));
    assertFalse(json.has("stringValue"));
    assertFalse(json.has("dateValue"));
    assertFalse(json.has("calendarValue"));
    assertFalse(json.has("objectValue"));
}

From source file:fi.kinetik.android.currencies.spi.openexchange.OpenExchangeRatesSpi.java

private void parseRates(ArrayList<ContentProviderOperation> operations, JSONObject jsonObj)
        throws JSONException {

    final long updated = jsonObj.getLong(Keys.TIMESTAMP);
    final String base = jsonObj.getString(Keys.BASE);
    final JSONObject rates = jsonObj.getJSONObject(Keys.RATES);
    final Iterator iter = rates.keys();

    while (iter.hasNext()) {

        final String currency = (String) iter.next();
        final double rate = rates.getDouble(currency);

        operations.add(ConversionRate.newUpdateOperation(currency, OpenExchangeRatesSpiFactory.PROVIDER_NAME,
                updated, rate));//from  www  .  j  a v  a2  s .  c  o  m
    }

}

From source file:edu.msu.walajahi.sunshine.app.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  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) {
            // Student: call bulkInsert to add the weatherEntries to the database here
            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:ru.neverdark.phototools.utils.Geocoder.java

/**
 * Gets coordinate from location name//from w  ww  . ja  v a  2 s  . c o  m
 * 
 * @param searchString
 *            user specify location name
 * @return coordinates for founded location or null if not found
 */
public LatLng getFromLocation(String searchString) {
    LatLng coords = null;
    String locationInfo = getLocationInfo(searchString);

    if (locationInfo.length() > 0) {
        try {
            JSONObject jsonObject = new JSONObject(locationInfo);
            JSONArray jsonArray = (JSONArray) jsonObject.get("results");
            JSONObject jsonLocation = jsonArray.getJSONObject(0).getJSONObject("geometry")
                    .getJSONObject("location");
            Double longitude = jsonLocation.getDouble("lng");
            Double latitude = jsonLocation.getDouble("lat");

            coords = new LatLng(latitude, longitude);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return coords;
}

From source file:com.extremeboredom.wordattack.utils.JSONUtils.java

/**
 * get Double from jsonObject/*from w  w  w  . j  av a 2s. co  m*/
 *
 * @param jsonObject
 * @param key
 * @param defaultValue
 * @return <ul>
 * <li>if jsonObject is null, return defaultValue</li>
 * <li>if key is null or empty, return defaultValue</li>
 * <li>if {@link JSONObject#getDouble(String)} exception, return defaultValue</li>
 * <li>return {@link JSONObject#getDouble(String)}</li>
 * </ul>
 */
public static Double getDouble(JSONObject jsonObject, String key, Double defaultValue) {
    if (jsonObject == null || StringUtils.isEmpty(key)) {
        return defaultValue;
    }

    try {
        return jsonObject.getDouble(key);
    } catch (JSONException e) {
        if (isPrintException) {
            e.printStackTrace();
        }
        return defaultValue;
    }
}

From source file:com.ibm.iot.auto.bluemix.samples.ui.InputData.java

public List<CarProbe> getCarProbes() throws IOException, JSONException {
    List<CarProbe> carProbes = new ArrayList<CarProbe>();

    FileReader fileReader = null;
    try {/*from www.  j a v  a  2s  . co  m*/
        fileReader = new FileReader(inputFile);
        JSONTokener jsonTokener = new JSONTokener(fileReader);
        JSONArray cars = new JSONArray(jsonTokener);
        for (int i = 0; i < cars.length(); i++) {
            JSONObject car = cars.getJSONObject(i);
            CarProbe carProbe = new CarProbe(car.getString("trip_id"), car.getString("timestamp"),
                    car.getDouble("heading"), car.getDouble("speed"), car.getDouble("longitude"),
                    car.getDouble("latitude"));
            carProbes.add(carProbe);
        }
    } finally {
        if (fileReader != null) {
            fileReader.close();
        }
    }
    Collections.sort(carProbes);

    return carProbes;
}