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.hunch.api.HunchAPI.java

public void searchForTopic(String query, final HunchTopic.ListCallback completedCallback) {
    if (query == null)
        throw new IllegalArgumentException("must set query!");

    HunchAPIRequest searchForTopicRequest = new HunchAPIRequest("searchForTopic");

    searchForTopicRequest.addParam("query", query);

    searchForTopicRequest.execute(new HunchAPIResponseCallback() {

        @Override/*from  www  .j  a  v a2  s .com*/
        public void callComplete(JSONObject j) {
            JSONArray topics;
            List<IHunchTopic> resultList = new ArrayList<IHunchTopic>();

            try {
                topics = j.getJSONArray("topics");
            } catch (JSONException e) {
                throw new RuntimeException("could not execute searchForTopic!", e);
            }

            for (int i = 0; i < topics.length(); i++) {
                JSONObject topic;

                try {
                    topic = topics.getJSONObject(i);
                } catch (JSONException e) {
                    throw new RuntimeException("couldn't build HunchTopic!", e);
                }

                if (topic == null)
                    break;

                HunchTopic hTopic;
                HunchTopic.Builder b = HunchTopic.getBuilder();

                int id;
                double score;
                String decision, urlName;

                try {
                    id = topic.getInt("id");
                    score = topic.getDouble("score");
                    decision = topic.getString("decision");
                    urlName = topic.getString("urlName");
                } catch (JSONException e) {
                    throw new RuntimeException("couldn't build HunchTopic!", e);
                }

                b.init(topic).setId(String.valueOf(id)).setDecision(decision).setUrlName(urlName)
                        .setScore(score);

                hTopic = b.buildForSearch();
                resultList.add(hTopic);

            }

            completedCallback.callComplete(resultList);
        }
    });

}

From source file:be.brunoparmentier.openbikesharing.app.parsers.BikeNetworkParser.java

public BikeNetworkParser(String toParse, boolean stripIdFromStationName) throws ParseException {
    ArrayList<Station> stations = new ArrayList<>();

    try {//  w w w  .  j a  v a 2 s.  c o m
        JSONObject jsonObject = new JSONObject(toParse);
        JSONObject rawNetwork = jsonObject.getJSONObject("network");

        /* network name & id */
        String networkId = rawNetwork.getString("id");
        String networkName = rawNetwork.getString("name");
        String networkCompany = rawNetwork.getString("company");

        /* network location */
        BikeNetworkLocation networkLocation;
        {
            JSONObject rawLocation = rawNetwork.getJSONObject("location");

            double latitude = rawLocation.getDouble("latitude");
            double longitude = rawLocation.getDouble("longitude");
            String city = rawLocation.getString("city");
            String country = rawLocation.getString("country");

            networkLocation = new BikeNetworkLocation(latitude, longitude, city, country);
        }

        /* stations list */
        {
            JSONArray rawStations = rawNetwork.getJSONArray("stations");

            for (int i = 0; i < rawStations.length(); i++) {
                JSONObject rawStation = rawStations.getJSONObject(i);

                String id = rawStation.getString("id");
                String name = rawStation.getString("name");
                if (stripIdFromStationName)
                    name = name.replaceAll("^[0-9 ]*- *", "");
                String lastUpdate = rawStation.getString("timestamp");
                double latitude = rawStation.getDouble("latitude");
                double longitude = rawStation.getDouble("longitude");
                int freeBikes = rawStation.getInt("free_bikes");
                int emptySlots;
                if (!rawStation.isNull("empty_slots")) {
                    emptySlots = rawStation.getInt("empty_slots");
                } else {
                    emptySlots = -1;
                }

                Station station = new Station(id, name, lastUpdate, latitude, longitude, freeBikes, emptySlots);

                /* extra info */
                if (rawStation.has("extra")) {
                    JSONObject rawExtra = rawStation.getJSONObject("extra");

                    /* address */
                    if (rawExtra.has("address")) {
                        station.setAddress(rawExtra.getString("address"));
                    } else if (rawExtra.has("description")) {
                        station.setAddress(rawExtra.getString("description"));
                    }

                    /* banking */
                    if (rawExtra.has("banking")) { // JCDecaux
                        station.setBanking(rawExtra.getBoolean("banking"));
                    } else if (rawExtra.has("payment")) {
                        if (rawExtra.getString("payment").equals("AVEC_TPE")) { // vlille
                            station.setBanking(true);
                        } else {
                            station.setBanking(false);
                        }
                    } else if (rawExtra.has("ticket")) { // dublinbikes, citycycle
                        station.setBanking(rawExtra.getBoolean("ticket"));
                    }

                    /* bonus */
                    if (rawExtra.has("bonus")) {
                        station.setBonus(rawExtra.getBoolean("bonus"));
                    }

                    /* status */
                    if (rawExtra.has("status")) {
                        String status = rawExtra.getString("status");
                        if (status.equals("CLOSED") // villo
                                || status.equals("CLS") // ClearChannel
                                || status.equals("1") // vlille
                                || status.equals("offline")) { // idecycle
                            station.setStatus(StationStatus.CLOSED);
                        } else {
                            station.setStatus(StationStatus.OPEN);
                        }
                    } else if (rawExtra.has("statusValue")) {
                        if (rawExtra.getString("statusValue").equals("Not In Service")) { // Bike Share
                            station.setStatus(StationStatus.CLOSED);
                        } else {
                            station.setStatus(StationStatus.OPEN);
                        }
                    } else if (rawExtra.has("locked")) {
                        if (rawExtra.getBoolean("locked")) { // bixi
                            station.setStatus(StationStatus.CLOSED);
                        } else {
                            station.setStatus(StationStatus.OPEN);
                        }
                    } else if (rawExtra.has("open")) {
                        if (!rawExtra.getBoolean("open")) { // dublinbikes, citycycle
                            station.setStatus(StationStatus.CLOSED);
                        } else {
                            station.setStatus(StationStatus.OPEN);
                        }
                    }
                }
                stations.add(station);
            }
        }

        bikeNetwork = new BikeNetwork(networkId, networkName, networkCompany, networkLocation, stations);
    } catch (JSONException e) {
        throw new ParseException("Error parsing JSON", 0);
    }
}

From source file:com.foxykeep.datadroidpoc.data.factory.PhoneAddEditFactory.java

public static Phone parseResult(String wsResponse) throws DataException {
    Phone phone = new Phone();

    try {/*from  w ww  .  ja va2 s.com*/
        JSONObject parser = new JSONObject(wsResponse);
        JSONObject jsonPhone = parser.getJSONObject(JSONTag.CRUD_PHONE_ADD_EDIT_ELEM_PHONE);

        phone.serverId = jsonPhone.getLong(JSONTag.CRUD_PHONE_ADD_EDIT_ELEM_ID);
        phone.name = jsonPhone.getString(JSONTag.CRUD_PHONE_ADD_EDIT_ELEM_NAME);
        phone.manufacturer = jsonPhone.getString(JSONTag.CRUD_PHONE_ADD_EDIT_ELEM_MANUFACTURER);
        phone.androidVersion = jsonPhone.getString(JSONTag.CRUD_PHONE_ADD_EDIT_ELEM_ANDROID_VERSION);
        phone.screenSize = jsonPhone.getDouble(JSONTag.CRUD_PHONE_ADD_EDIT_ELEM_SCREEN_SIZE);
        phone.price = jsonPhone.getInt(JSONTag.CRUD_PHONE_ADD_EDIT_ELEM_PRICE);
    } catch (JSONException e) {
        Log.e(TAG, "JSONException", e);
        throw new DataException(e);
    }

    return phone;
}

From source file:jatoo.weather.openweathermap.AbstractJaTooWeatherOpenWeatherMap.java

@Override
protected final JaTooWeather getWeatherImpl(final String city) throws Throwable {

    JSONObject json = new JSONObject(getJSONResponse(city));

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(json.toString(2));/*from   w ww  .ja  va 2s  .co  m*/
    }

    JSONObject jsonWeather = json.getJSONArray("weather").getJSONObject(0);
    JSONObject jsonMain = json.getJSONObject("main");
    JSONObject jsonWind = json.getJSONObject("wind");
    JSONObject jsonClouds = json.getJSONObject("clouds");
    JSONObject jsonSys = json.getJSONObject("sys");

    JaTooWeather weather = new JaTooWeather(this);

    weather.setCity(json.getString("name"));

    weather.setDescription(jsonWeather.getString("description"));

    weather.setTemperature(jsonMain.getDouble("temp"));
    weather.setTemperatureUnit(JaTooWeather.TEMPERATURE_UNIT.CELSIUS);

    weather.setHumidity(jsonMain.getInt("humidity"));
    weather.setHumidityUnit(JaTooWeather.HUMIDITY_UNIT.PERCENT);

    weather.setPressure(jsonMain.getDouble("pressure"));
    weather.setPressureUnit(JaTooWeather.PRESSURE_UNIT.HPA);

    weather.setWind(jsonWind.getDouble("speed"));
    weather.setWindUnit(JaTooWeather.WIND_UNIT.METER_PER_SEC);

    weather.setWindDirection(jsonWind.getDouble("deg"));
    weather.setWindDirectionUnit(JaTooWeather.WIND_DIRECTION_UNIT.DEGREES_METEOROLOGICAL);

    weather.setClouds(jsonClouds.getInt("all"));
    weather.setCloudsUnit(JaTooWeather.CLOUDS_UNIT.PERCENT);

    weather.setSunrise(TimeUnit.SECONDS.toMillis(jsonSys.getLong("sunrise")));
    weather.setSunset(TimeUnit.SECONDS.toMillis(jsonSys.getLong("sunset")));

    return weather;
}

From source file:app.com.example.android.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   ww  w  . ja  v  a2  s  .  c  om*/
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.
 */
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);
            // Student: call bulkInsert to add the weatherEntries to the database here
            inserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
        }
        Log.d(LOG_TAG, "FetchWeatherTask Complete. " + cVVector.size() + "Inserted");

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

From source file:com.synox.android.ui.activity.FileActivity.java

/**
 * Retrieves user quota if available//from   w  w w .j  a va  2 s . c  om
 *
 * @param navigationDrawerLayout
 */
private void getUserQuota(final NavigationView navigationDrawerLayout, final String user) {
    // set user space information
    Thread t = new Thread(new Runnable() {
        public void run() {

            try {
                OwnCloudAccount ocAccount = new OwnCloudAccount(mAccount, MainApp.getAppContext());

                OwnCloudClient client = OwnCloudClientManagerFactory.getDefaultSingleton()
                        .getClientFor(ocAccount, MainApp.getAppContext());
                GetMethod get = null;

                final ProgressBar quotaProgress = (ProgressBar) navigationDrawerLayout
                        .findViewById(R.id.usage_progress);
                final LinearLayout quotaInformation = (LinearLayout) navigationDrawerLayout
                        .findViewById(R.id.quotaInformation);

                try {
                    get = new GetMethod(
                            client.getBaseUri() + "/ocs/v1.php/cloud/users/" + user + "?format=json");
                    int status = client.executeMethod(get);
                    if (status == HttpStatus.SC_OK) {
                        JSONObject json = new JSONObject(get.getResponseBodyAsString());
                        JSONObject ocs = json.getJSONObject("ocs");
                        JSONObject meta = ocs.getJSONObject("meta");
                        JSONObject data = ocs.getJSONObject("data");
                        JSONObject quota = data.getJSONObject("quota");
                        if (meta.getString("statuscode").equals("100")) {

                            try {
                                final long used = Long.parseLong(quota.getString("used"));
                                final long total = Long.parseLong(quota.getString("total"));
                                final int relative = (int) Math.ceil(quota.getDouble("relative"));

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (quotaProgress != null) {

                                            if (quotaInformation.getVisibility() == View.INVISIBLE) {
                                                Animation animation = AnimationUtils.loadAnimation(
                                                        navigationDrawerLayout.getContext(),
                                                        R.anim.abc_slide_in_bottom);
                                                quotaInformation.setAnimation(animation);
                                            }
                                            quotaInformation.setVisibility(View.VISIBLE);
                                            quotaProgress.setProgress(relative);
                                        } else {
                                            quotaInformation.setVisibility(View.INVISIBLE);
                                        }

                                        TextView usageText = (TextView) navigationDrawerLayout
                                                .findViewById(R.id.usage_text);
                                        usageText.setText(String.format(getString(R.string.usage_text),
                                                DisplayUtils.bytesToHumanReadable(used),
                                                DisplayUtils.bytesToHumanReadable(total)));

                                    }
                                });

                            } catch (NumberFormatException nfe) {
                                Log_OC.e(this.getClass().getName(),
                                        "Error retrieving quota usage from server.");
                            }
                        }
                    } else {
                        client.exhaustResponse(get.getResponseBodyAsStream());
                    }
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            quotaInformation.setVisibility(View.INVISIBLE);
                            e.printStackTrace();
                        }
                    });
                } finally

                {
                    if (get != null) {
                        get.releaseConnection();
                    }
                }

            } catch (com.synox.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) {
                Log_OC.e(this.getClass().getName(), e.getMessage());
            } catch (AuthenticatorException | OperationCanceledException | IOException e) {
                Log_OC.e(this.getClass().getName(), e.getMessage());
            }
        }
    });
    t.start();
}

From source file:com.njlabs.amrita.aid.landing.Landing.java

public void checkForUpdates() {

    OkHttpClient client = new OkHttpClient.Builder().followRedirects(true).followSslRedirects(true).build();

    Request.Builder request = new Request.Builder().url("https://api.codezero.xyz/aid/latest");

    client.newCall(request.build()).enqueue(new Callback() {
        @Override/*from  w  ww  . j a  v  a 2 s  .  c  o  m*/
        public void onFailure(Call call, IOException e) {
            Ln.e(e);
        }

        @Override
        public void onResponse(Call call, final Response rawResponse) throws IOException {
            final String responseString = rawResponse.body().string();
            ((Activity) baseContext).runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    JSONObject response;

                    try {
                        response = new JSONObject(responseString);

                        String status = "";
                        status = response.getString("status");

                        if (status.equals("ok")) {
                            Double Latest = 0.0;
                            String Description = null;
                            try {
                                Latest = response.getDouble("version");
                                Description = response.getString("description");
                            } catch (JSONException e) {
                                FirebaseCrash.report(e);
                            }
                            if (Latest > BuildConfig.VERSION_CODE) {

                                AlertDialog.Builder updateDialogBuilder = new AlertDialog.Builder(Landing.this);

                                LayoutInflater factory = LayoutInflater.from(Landing.this);
                                final View changelogView = factory.inflate(R.layout.webview_dialog, null);
                                LinearLayout WebViewDialogLayout = (LinearLayout) changelogView
                                        .findViewById(R.id.WebViewDialogLayout);
                                WebViewDialogLayout.setPadding(5, 5, 5, 5);
                                WebView changelogWebView = (WebView) changelogView
                                        .findViewById(R.id.LicensesView);
                                changelogWebView.loadData(String.format("%s", Description), "text/html",
                                        "utf-8");
                                changelogWebView.setPadding(5, 5, 5, 5);
                                changelogWebView.setBackgroundColor(0);
                                changelogWebView.setOnLongClickListener(new View.OnLongClickListener() {
                                    @Override
                                    public boolean onLongClick(View v) {
                                        return true;
                                    }
                                });
                                changelogWebView.setLongClickable(false);
                                updateDialogBuilder.setView(changelogView).setCancelable(true)
                                        .setCancelable(false)
                                        .setNegativeButton("Dismiss", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int id) {
                                                dialog.cancel();
                                            }
                                        })
                                        .setPositiveButton("Update Now", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int id) {
                                                Uri uri = Uri
                                                        .parse("market://details?id=com.njlabs.amrita.aid");
                                                Intent it = new Intent(Intent.ACTION_VIEW, uri);
                                                startActivity(it);
                                            }
                                        });
                                AlertDialog alert = updateDialogBuilder.create();
                                alert.setTitle("Update Available");
                                alert.setIcon(R.mipmap.ic_launcher);
                                alert.show();
                            }
                        }

                    } catch (Exception e) {
                        Ln.e(e);
                    }
                }
            });
        }
    });
}

From source file:udatraining.dyomin.com.udaproj1.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 a  v  a2s  .  c  o 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(WeatherContract.WeatherEntry.COLUMN_LOC_KEY, locationId);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DATE, dateTime);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_HUMIDITY, humidity);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_PRESSURE, pressure);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DEGREES, windDirection);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, high);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, low);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_SHORT_DESC, description);
            weatherValues.put(WeatherContract.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(WeatherContract.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:com.yahoo.egads.data.JsonEncoder.java

public static void fromJson(Object object, JSONObject json_obj) throws Exception {
    // for each json key-value, that has a corresponding variable in object ...
    for (Iterator k = json_obj.keys(); k.hasNext();) {
        String key = (String) k.next();
        Object value = json_obj.get(key);

        // try to access object variable
        Field field = null;// w w  w .j  a v  a 2s .c  o  m
        try {
            field = object.getClass().getField(key);
        } catch (Exception e) {
            continue;
        }
        if (Modifier.isStatic(field.getModifiers())) {
            continue;
        }
        if (Modifier.isPrivate(field.getModifiers())) {
            continue;
        }
        Object member = field.get(object);

        if (json_obj.isNull(key)) {
            field.set(object, null);
            continue;
            // if variable is container... recurse
        } else if (member instanceof JsonAble) {
            ((JsonAble) member).fromJson((JSONObject) value);
            // if variable is an array... recurse on sub-objects
        } else if (member instanceof ArrayList) {
            // Depends on existance of ArrayList<T> template parameter, and T constructor with no arguments.
            // May be better to use custom fromJson() in member class.
            ArrayList memberArray = (ArrayList) member;
            JSONArray jsonArray = (JSONArray) value;

            // find array element constructor
            ParameterizedType arrayType = null;
            if (field.getGenericType() instanceof ParameterizedType) {
                arrayType = (ParameterizedType) field.getGenericType();
            }
            for (Class c = member.getClass(); arrayType == null && c != null; c = c.getSuperclass()) {
                if (c.getGenericSuperclass() instanceof ParameterizedType) {
                    arrayType = (ParameterizedType) c.getGenericSuperclass();
                }
            }
            if (arrayType == null) {
                throw new Exception("could not find ArrayList element type for field 'key'");
            }
            Class elementClass = (Class) (arrayType.getActualTypeArguments()[0]);
            Constructor elementConstructor = elementClass.getConstructor();

            // for each element in JSON array ... append element to member array, recursively decode element
            for (int i = 0; i < jsonArray.length(); ++i) {
                Object element = elementConstructor.newInstance();
                fromJson(element, jsonArray.getJSONObject(i));
                memberArray.add(element);
            }
            // if variable is simple value... set
        } else if (field.getType() == float.class) {
            field.set(object, (float) json_obj.getDouble(key));
        } else {
            field.set(object, value);
        }
    }
}

From source file:net.phase.wallet.Currency.java

public static double getRate(String currency) {
    double result = 0;

    if (lastResult != null) {
        try {/*from w  w w . ja v a2  s .  co  m*/
            // JSONObject.keys() returns Iterator<String> but for some
            // reason
            // isn't typed that way
            @SuppressWarnings("unchecked")
            Iterator<String> itr = lastResult.keys();

            // look through every transaction
            while (itr.hasNext()) {
                String cur = itr.next();
                if (cur.equals(currency)) {
                    JSONObject currencyObject = lastResult.getJSONObject(cur);
                    try {
                        result = currencyObject.getDouble("30d");
                        result = currencyObject.getDouble("7d");
                        result = currencyObject.getDouble("24h");
                    } catch (JSONException e) {
                        // caught when the first failure occurs above
                    }
                }
            }
        } catch (JSONException e) {

        }
    }

    return result;
}