Example usage for org.json JSONObject getLong

List of usage examples for org.json JSONObject getLong

Introduction

In this page you can find the example usage for org.json JSONObject getLong.

Prototype

public long getLong(String key) throws JSONException 

Source Link

Document

Get the long value associated with a key.

Usage

From source file:com.panduka.weatherforecast.utils.DataResolver.java

/**
 * High level data initializing to custom data structures by extracting the JSON passed.
 *
 * @param json JSON String object//  w  w w .  j  a va2 s.com
 */
public void initialize(String json) throws JSONException {
    JSONObject jsonObj = new JSONObject(json);
    mForecast = new Forecast();
    //extract JSON objects
    mForecast.latitude = jsonObj.getLong("latitude");
    mForecast.longitude = jsonObj.getLong("longitude");
    mForecast.timezone = jsonObj.getString("timezone");
    mForecast.offset = jsonObj.getString("offset");

    //extract JSON objects and create respective weather data structures
    mForecast.currently = createHourlyData(jsonObj.getJSONObject("currently"));
    mForecast.hourly = createHourlyStruct(jsonObj.getJSONObject("hourly"));
    mForecast.daily = createDailyStruct(jsonObj.getJSONObject("daily"));
    mForecast.flags = createFlags(jsonObj.getJSONObject("flags"));

    if (jsonObj.has("alerts")) {
        mForecast.alerts = createAlerts(jsonObj.getJSONArray("alerts"));
    }
}

From source file:com.panduka.weatherforecast.utils.DataResolver.java

private HourlyData createHourlyData(JSONObject jsonObject) throws JSONException {
    HourlyData hourlyData = new HourlyData();
    hourlyData.time = jsonObject.getLong("time");
    hourlyData.summary = jsonObject.getString("summary");
    hourlyData.icon = jsonObject.getString("icon");
    hourlyData.precipIntensity = jsonObject.getDouble("precipIntensity");
    hourlyData.precipProbability = jsonObject.getDouble("precipProbability");
    hourlyData.temperature = jsonObject.getDouble("temperature");
    hourlyData.apparentTemperature = jsonObject.getDouble("apparentTemperature");
    hourlyData.dewPoint = jsonObject.getDouble("dewPoint");
    hourlyData.humidity = jsonObject.getDouble("humidity");
    hourlyData.windSpeed = jsonObject.getDouble("windSpeed");
    hourlyData.windBearing = jsonObject.getInt("windBearing");
    hourlyData.cloudCover = jsonObject.getDouble("cloudCover");
    hourlyData.pressure = jsonObject.getDouble("pressure");
    hourlyData.ozone = jsonObject.getDouble("ozone");
    return hourlyData;
}

From source file:com.panduka.weatherforecast.utils.DataResolver.java

private DailyData createDailyData(JSONObject jsonObject) throws JSONException {
    DailyData dailyData = new DailyData();
    dailyData.time = jsonObject.getLong("time");
    dailyData.summary = jsonObject.getString("summary");
    dailyData.icon = jsonObject.getString("icon");
    dailyData.sunriseTime = jsonObject.getLong("sunriseTime");
    dailyData.sunsetTime = jsonObject.getLong("sunsetTime");
    dailyData.moonPhase = jsonObject.getDouble("moonPhase");
    dailyData.precipIntensity = jsonObject.getDouble("precipIntensity");
    dailyData.precipIntensityMax = jsonObject.getDouble("precipIntensityMax");

    if (jsonObject.has("precipIntensityMaxTime")) {
        dailyData.precipIntensityMaxTime = jsonObject.getLong("precipIntensityMaxTime"); //Service is inconsistent
    }/*  w ww. j ava2 s  .c o  m*/

    dailyData.precipProbability = jsonObject.getDouble("precipProbability");

    if (jsonObject.has("precipType")) {
        dailyData.precipType = jsonObject.getString("precipType"); //Service is inconsistent
    }

    dailyData.temperatureMin = jsonObject.getDouble("temperatureMin");
    dailyData.temperatureMinTime = jsonObject.getLong("temperatureMinTime");
    dailyData.temperatureMax = jsonObject.getDouble("temperatureMax");
    dailyData.temperatureMaxTime = jsonObject.getLong("temperatureMaxTime");
    dailyData.apparentTemperatureMin = jsonObject.getDouble("apparentTemperatureMin");
    dailyData.apparentTemperatureMinTime = jsonObject.getLong("apparentTemperatureMinTime");
    dailyData.apparentTemperatureMax = jsonObject.getDouble("apparentTemperatureMax");
    dailyData.apparentTemperatureMaxTime = jsonObject.getLong("apparentTemperatureMaxTime");
    dailyData.dewPoint = jsonObject.getDouble("dewPoint");
    dailyData.humidity = jsonObject.getDouble("humidity");
    dailyData.windSpeed = jsonObject.getDouble("windSpeed");
    dailyData.windBearing = jsonObject.getInt("windBearing");
    dailyData.cloudCover = jsonObject.getDouble("cloudCover");
    dailyData.pressure = jsonObject.getDouble("pressure");
    dailyData.ozone = jsonObject.getDouble("ozone");
    return dailyData;
}

From source file:ch.ethz.twimight.net.opportunistic.ScanningService.java

private void processHtml(JSONObject o) {
    try {//from ww w.  ja  v  a  2  s. c o  m
        Log.i(TAG, "process HTML");
        String xmlContent = o.getString(HtmlPage.COL_HTML);
        String filename = o.getString(HtmlPage.COL_FILENAME);
        Long tweetId = o.getLong(HtmlPage.COL_DISASTERID);
        String htmlUrl = o.getString(HtmlPage.COL_URL);

        String[] filePath = { HtmlPage.HTML_PATH + "/" + LoginActivity.getTwitterId(getApplicationContext()) };
        if (sdCardHelper.checkSDState(filePath)) {
            File targetFile = sdCardHelper.getFileFromSDCard(filePath[0], filename);// photoFileParent,
            // photoFilename));
            if (saveFile(targetFile, xmlContent)) {
                // downloaded = 1;
            }
        }
        htmlDbHelper.insertPage(htmlUrl, filename, tweetId, 0);

    } catch (JSONException e1) {
        Log.e(TAG, "Exception while receiving disaster tweet photo", e1);
    }
}

From source file:ch.ethz.twimight.net.opportunistic.ScanningService.java

/**
 * Creates content values for a Tweet from a JSON object TODO: Move this to
 * where it belongs/* w ww . ja  v a  2 s . c o  m*/
 * 
 * @param o
 * @return
 * @throws JSONException
 */
protected ContentValues getTweetCV(JSONObject o) throws JSONException {

    ContentValues cv = new ContentValues();

    if (o.has(Tweets.COL_CERTIFICATE))
        cv.put(Tweets.COL_CERTIFICATE, o.getString(Tweets.COL_CERTIFICATE));

    if (o.has(Tweets.COL_SIGNATURE))
        cv.put(Tweets.COL_SIGNATURE, o.getString(Tweets.COL_SIGNATURE));

    if (o.has(Tweets.COL_CREATED_AT))
        cv.put(Tweets.COL_CREATED_AT, o.getLong(Tweets.COL_CREATED_AT));

    if (o.has(Tweets.COL_TEXT)) {
        cv.put(Tweets.COL_TEXT, o.getString(Tweets.COL_TEXT));
        cv.put(Tweets.COL_TEXT_PLAIN, Html.fromHtml(o.getString(Tweets.COL_TEXT)).toString());
    }

    if (o.has(Tweets.COL_USER_TID)) {
        cv.put(Tweets.COL_USER_TID, o.getLong(Tweets.COL_USER_TID));
    }

    if (o.has(Tweets.COL_TID)) {
        cv.put(Tweets.COL_TID, o.getLong(Tweets.COL_TID));
    }

    if (o.has(Tweets.COL_REPLY_TO_TWEET_TID))
        cv.put(Tweets.COL_REPLY_TO_TWEET_TID, o.getLong(Tweets.COL_REPLY_TO_TWEET_TID));

    if (o.has(Tweets.COL_LAT))
        cv.put(Tweets.COL_LAT, o.getDouble(Tweets.COL_LAT));

    if (o.has(Tweets.COL_LNG))
        cv.put(Tweets.COL_LNG, o.getDouble(Tweets.COL_LNG));

    if (o.has(Tweets.COL_SOURCE))
        cv.put(Tweets.COL_SOURCE, o.getString(Tweets.COL_SOURCE));

    if (o.has(Tweets.COL_MEDIA_URIS)) {
        String userID = cv.getAsString(Tweets.COL_USER_TID);
        photoPath = PHOTO_PATH + "/" + userID;
        String photoFileName = o.getString(Tweets.COL_MEDIA_URIS);
        File targetFile = sdCardHelper.getFileFromSDCard(photoPath, photoFileName);

        cv.put(Tweets.COL_MEDIA_URIS, Uri.fromFile(targetFile).toString());

    }

    if (o.has(Tweets.COL_HTML_PAGES))
        cv.put(Tweets.COL_HTML_PAGES, o.getString(Tweets.COL_HTML_PAGES));

    if (o.has(TwitterUsers.COL_SCREEN_NAME)) {
        cv.put(Tweets.COL_SCREEN_NAME, o.getString(TwitterUsers.COL_SCREEN_NAME));
    }

    return cv;
}

From source file:ch.ethz.twimight.net.opportunistic.ScanningService.java

/**
 * Creates content values for a DM from a JSON object
 * // ww  w. j  a v  a2s  .  com
 * @param o
 * @return
 * @throws JSONException
 */
private ContentValues getDmContentValues(JSONObject o) throws JSONException {

    ContentValues cv = new ContentValues();

    if (o.has(DirectMessages.COL_CERTIFICATE))
        cv.put(DirectMessages.COL_CERTIFICATE, o.getString(DirectMessages.COL_CERTIFICATE));

    if (o.has(DirectMessages.COL_SIGNATURE))
        cv.put(DirectMessages.COL_SIGNATURE, o.getString(DirectMessages.COL_SIGNATURE));

    if (o.has(DirectMessages.COL_CREATED))
        cv.put(DirectMessages.COL_CREATED, o.getLong(DirectMessages.COL_CREATED));

    if (o.has(DirectMessages.COL_CRYPTEXT))
        cv.put(DirectMessages.COL_CRYPTEXT, o.getString(DirectMessages.COL_CRYPTEXT));

    if (o.has(DirectMessages.COL_DISASTERID))
        cv.put(DirectMessages.COL_DISASTERID, o.getLong(DirectMessages.COL_DISASTERID));

    if (o.has(DirectMessages.COL_SENDER))
        cv.put(DirectMessages.COL_SENDER, o.getLong(DirectMessages.COL_SENDER));

    if (o.has(DirectMessages.COL_RECEIVER))
        cv.put(DirectMessages.COL_RECEIVER, o.getLong(DirectMessages.COL_RECEIVER));

    return cv;
}

From source file:ch.ethz.twimight.net.opportunistic.ScanningService.java

/**
 * Creates content values for a User from a JSON object TODO: Move this to
 * where it belongs/*from   w  ww. j  av  a 2s  . c  o  m*/
 * 
 * @param o
 * @return
 * @throws JSONException
 */
protected ContentValues getUserCV(JSONObject o) throws JSONException {

    // create the content values for the user
    ContentValues cv = new ContentValues();
    String screenName = null;

    if (o.has(TwitterUsers.COL_SCREEN_NAME)) {
        screenName = o.getString(TwitterUsers.COL_SCREEN_NAME);
        cv.put(TwitterUsers.COL_SCREEN_NAME, o.getString(TwitterUsers.COL_SCREEN_NAME));
    }

    if (o.has(TwitterUsers.JSON_FIELD_PROFILE_IMAGE) && screenName != null) {
        InternalStorageHelper helper = new InternalStorageHelper(getBaseContext());
        byte[] image = Base64.decode(o.getString(TwitterUsers.JSON_FIELD_PROFILE_IMAGE), Base64.DEFAULT);
        helper.writeImage(image, screenName);
        String profileImageUri = Uri.fromFile(new File(getFilesDir(), screenName)).toString();
        Log.d(TAG, "storing profile image at: " + profileImageUri);
        cv.put(TwitterUsers.COL_PROFILE_IMAGE_URI, profileImageUri);
    }

    if (o.has(Tweets.COL_USER_TID)) {
        cv.put(TwitterUsers.COL_TWITTER_USER_ID, o.getLong(Tweets.COL_USER_TID));

    }
    cv.put(TwitterUsers.COL_IS_DISASTER_PEER, 1);

    return cv;
}

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   www  .j  a v  a 2s  .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, 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:com.liferay.alerts.model.User.java

public User(String json) throws JSONException {
    JSONObject jsonObject = new JSONObject(json);

    _id = jsonObject.getLong("userId");
    _uuid = jsonObject.getString(User.UUID);
    _fullName = jsonObject.getString(User.FULL_NAME);
    _portraitId = jsonObject.getLong(User.PORTRAIT_ID);
}

From source file:edu.isi.misd.tagfiler.download.FileDownloadImplementation.java

/**
 * Gets the files to be downloaded./*from ww w .j a  v a2s. c  om*/
 */
private boolean getDataSet() throws Exception {
    boolean result = false;

    try {
        // get the "bytes" and "sha256sum" tags of the files
        JSONArray tagsValues = getFilesTagValues(applet, fileDownloadListener);
        if (tagsValues != null) {
            // get the number of files to be downloaded
            // by replacing a file with an URL, we might have have fewer files to be downloaded
            int totalFiles = tagsValues.length();
            for (int i = 0; i < tagsValues.length(); i++) {
                if (tagsValues.getJSONObject(i).isNull(BYTES)) {
                    totalFiles--;
                }
            }
            if (totalFiles > 0) {
                fileDownloadListener.notifyRetrieveStart(totalFiles);

                for (int i = 0; i < tagsValues.length(); i++) {
                    JSONObject fileTags = tagsValues.getJSONObject(i);

                    // make sure we have a file
                    if (fileTags.isNull(BYTES)) {
                        continue;
                    }

                    // get the file name
                    String file = fileTags.getString(NAME).substring(dataset.length() + 1);
                    fileNames.add(file);

                    // get the bytes
                    long bytes = fileTags.getLong(BYTES);
                    datasetSize += bytes;
                    bytesMap.put(file, bytes);

                    // get the version
                    String vname = fileTags.getString(VNAME);
                    int version = Integer.parseInt(vname.substring(vname.lastIndexOf("@") + 1));
                    versionMap.put(file, version);

                    // get the checksum
                    if (!fileTags.isNull(SHA256SUM)) {
                        String checksum = fileTags.getString(SHA256SUM);
                        checksumMap.put(file, checksum);
                    }
                    fileDownloadListener.notifyFileRetrieveComplete(file);
                }
            }
        }
        result = true;
    } catch (Exception e) {
        e.printStackTrace();
        fileDownloadListener.notifyError(e);
        result = false;
    }

    return result;
}