Example usage for android.content ContentValues getAsString

List of usage examples for android.content ContentValues getAsString

Introduction

In this page you can find the example usage for android.content ContentValues getAsString.

Prototype

public String getAsString(String key) 

Source Link

Document

Gets a value and converts it to a String.

Usage

From source file:app.com.example.wungmathing.sunshine.FetchWeatherTask.java

String[] convertContentValuesToUXFormat(Vector<ContentValues> cvv) {
    // return strings to keep UI functional for now
    String[] resultStrs = new String[cvv.size()];
    for (int i = 0; i < cvv.size(); i++) {
        ContentValues weatherValues = cvv.elementAt(i);
        String highAndLow = formatHighLows(weatherValues.getAsDouble(WeatherEntry.COLUMN_MAX_TEMP),
                weatherValues.getAsDouble(WeatherEntry.COLUMN_MIN_TEMP));
        resultStrs[i] = getReadableDateString(weatherValues.getAsLong(WeatherEntry.COLUMN_DATE)) + " - "
                + weatherValues.getAsString(WeatherEntry.COLUMN_SHORT_DESC) + " - " + highAndLow;
    }//from  w w  w .  j  a va2  s .  co  m
    return resultStrs;
}

From source file:at.bitfire.ical4android.AndroidEvent.java

protected void populateEvent(ContentValues values) {
    event.summary = values.getAsString(Events.TITLE);
    event.location = values.getAsString(Events.EVENT_LOCATION);
    event.description = values.getAsString(Events.DESCRIPTION);

    final boolean allDay = values.getAsInteger(Events.ALL_DAY) != 0;
    final long tsStart = values.getAsLong(Events.DTSTART);
    final String duration = values.getAsString(Events.DURATION);

    String tzId;/*w w  w.  ja  v  a 2s.co m*/
    Long tsEnd = values.getAsLong(Events.DTEND);
    if (allDay) {
        event.setDtStart(tsStart, null);
        if (tsEnd == null) {
            Dur dur = new Dur(duration);
            java.util.Date dEnd = dur.getTime(new java.util.Date(tsStart));
            tsEnd = dEnd.getTime();
        }
        event.setDtEnd(tsEnd, null);

    } else {
        // use the start time zone for the end time, too
        // because apps like Samsung Planner allow the user to change "the" time zone but change the start time zone only
        tzId = values.getAsString(Events.EVENT_TIMEZONE);
        event.setDtStart(tsStart, tzId);
        if (tsEnd != null)
            event.setDtEnd(tsEnd, tzId);
        else if (!StringUtils.isEmpty(duration))
            event.duration = new Duration(new Dur(duration));
    }

    // recurrence
    try {
        String strRRule = values.getAsString(Events.RRULE);
        if (!StringUtils.isEmpty(strRRule))
            event.rRule = new RRule(strRRule);

        String strRDate = values.getAsString(Events.RDATE);
        if (!StringUtils.isEmpty(strRDate)) {
            RDate rDate = (RDate) DateUtils.androidStringToRecurrenceSet(strRDate, RDate.class, allDay);
            event.getRDates().add(rDate);
        }

        String strExRule = values.getAsString(Events.EXRULE);
        if (!StringUtils.isEmpty(strExRule)) {
            ExRule exRule = new ExRule();
            exRule.setValue(strExRule);
            event.exRule = exRule;
        }

        String strExDate = values.getAsString(Events.EXDATE);
        if (!StringUtils.isEmpty(strExDate)) {
            ExDate exDate = (ExDate) DateUtils.androidStringToRecurrenceSet(strExDate, ExDate.class, allDay);
            event.getExDates().add(exDate);
        }
    } catch (ParseException ex) {
        Log.w(TAG, "Couldn't parse recurrence rules, ignoring", ex);
    } catch (IllegalArgumentException ex) {
        Log.w(TAG, "Invalid recurrence rules, ignoring", ex);
    }

    if (values.containsKey(Events.ORIGINAL_INSTANCE_TIME)) {
        // this event is an exception of a recurring event
        long originalInstanceTime = values.getAsLong(Events.ORIGINAL_INSTANCE_TIME);

        boolean originalAllDay = false;
        if (values.containsKey(Events.ORIGINAL_ALL_DAY))
            originalAllDay = values.getAsInteger(Events.ORIGINAL_ALL_DAY) != 0;

        Date originalDate = originalAllDay ? new Date(originalInstanceTime)
                : new DateTime(originalInstanceTime);
        if (originalDate instanceof DateTime)
            ((DateTime) originalDate).setUtc(true);
        event.recurrenceId = new RecurrenceId(originalDate);
    }

    // status
    if (values.containsKey(Events.STATUS))
        switch (values.getAsInteger(Events.STATUS)) {
        case Events.STATUS_CONFIRMED:
            event.status = Status.VEVENT_CONFIRMED;
            break;
        case Events.STATUS_TENTATIVE:
            event.status = Status.VEVENT_TENTATIVE;
            break;
        case Events.STATUS_CANCELED:
            event.status = Status.VEVENT_CANCELLED;
        }

    // availability
    event.opaque = values.getAsInteger(Events.AVAILABILITY) != Events.AVAILABILITY_FREE;

    // set ORGANIZER if there's attendee data
    if (values.getAsInteger(Events.HAS_ATTENDEE_DATA) != 0 && values.containsKey(Events.ORGANIZER))
        try {
            event.organizer = new Organizer(new URI("mailto", values.getAsString(Events.ORGANIZER), null));
        } catch (URISyntaxException ex) {
            Log.e(TAG, "Error when creating ORGANIZER mailto URI, ignoring", ex);
        }

    // classification
    switch (values.getAsInteger(Events.ACCESS_LEVEL)) {
    case Events.ACCESS_CONFIDENTIAL:
    case Events.ACCESS_PRIVATE:
        event.forPublic = false;
        break;
    case Events.ACCESS_PUBLIC:
        event.forPublic = true;
    }
}

From source file:at.bitfire.ical4android.AndroidEvent.java

@TargetApi(16)
protected void populateAttendee(ContentValues values) {
    try {/* ww  w .  j av a 2  s.  c o  m*/
        final Attendee attendee;
        final String email = values.getAsString(Attendees.ATTENDEE_EMAIL), idNS, id;
        if (Build.VERSION.SDK_INT >= 16) {
            idNS = values.getAsString(Attendees.ATTENDEE_ID_NAMESPACE);
            id = values.getAsString(Attendees.ATTENDEE_IDENTITY);
        } else
            idNS = id = null;

        if (idNS != null || id != null) {
            // attendee identified by namespace and ID
            attendee = new Attendee(new URI(idNS, id, null));
            if (email != null)
                attendee.getParameters().add(new iCalendar.Email(email));
        } else
            // attendee identified by email address
            attendee = new Attendee(new URI("mailto", email, null));
        final ParameterList params = attendee.getParameters();

        String cn = values.getAsString(Attendees.ATTENDEE_NAME);
        if (cn != null)
            params.add(new Cn(cn));

        // type
        int type = values.getAsInteger(Attendees.ATTENDEE_TYPE);
        params.add((type == Attendees.TYPE_RESOURCE) ? CuType.RESOURCE : CuType.INDIVIDUAL);

        // role
        int relationship = values.getAsInteger(Attendees.ATTENDEE_RELATIONSHIP);
        switch (relationship) {
        case Attendees.RELATIONSHIP_ORGANIZER:
        case Attendees.RELATIONSHIP_ATTENDEE:
        case Attendees.RELATIONSHIP_PERFORMER:
        case Attendees.RELATIONSHIP_SPEAKER:
            params.add((type == Attendees.TYPE_REQUIRED) ? Role.REQ_PARTICIPANT : Role.OPT_PARTICIPANT);
            params.add(new Rsvp(true));
            break;
        case Attendees.RELATIONSHIP_NONE:
            params.add(Role.NON_PARTICIPANT);
        }

        // status
        switch (values.getAsInteger(Attendees.ATTENDEE_STATUS)) {
        case Attendees.ATTENDEE_STATUS_INVITED:
            params.add(PartStat.NEEDS_ACTION);
            break;
        case Attendees.ATTENDEE_STATUS_ACCEPTED:
            params.add(PartStat.ACCEPTED);
            break;
        case Attendees.ATTENDEE_STATUS_DECLINED:
            params.add(PartStat.DECLINED);
            break;
        case Attendees.ATTENDEE_STATUS_TENTATIVE:
            params.add(PartStat.TENTATIVE);
            break;
        }

        event.getAttendees().add(attendee);
    } catch (URISyntaxException ex) {
        Log.e(TAG, "Couldn't parse attendee information, ignoring", ex);
    }
}

From source file:com.hybris.mobile.lib.commerce.provider.CatalogProvider.java

/**
 * Insert the new item or update it if already in database
 *
 * @param uri       String of characters used to identify a name of a resource
 * @param values    Set of content values
 * @param idName    Unique name string/*from   w  ww .  jav  a 2s . c o  m*/
 * @param tableName an element (data or group)
 */
private void insertOrUpdateGeneric(Uri uri, ContentValues values, String idName, String tableName) {
    try {
        Log.d(TAG, "Inserting the information for the item " + values.getAsString(idName));
        mDatabaseHelper.getWritableDatabase().insertOrThrow(tableName, null, values);
    } catch (SQLiteConstraintException e) {
        Log.d(TAG, "Item " + values.getAsString(idName) + " already exists, updating it");

        update(uri, values, idName + "=?", new String[] { values.getAsString(idName) });
    }
}

From source file:org.mariotaku.twidere.provider.TweetStoreProvider.java

private void onNewItemsInserted(final Uri uri, final int count, final ContentValues... values) {
    if (uri == null || values == null || values.length == 0 || count == 0)
        return;//ww  w .  jav a 2s  .c  om
    if ("false".equals(uri.getQueryParameter(QUERY_PARAM_NOTIFY)))
        return;
    final Context context = getContext();
    final Resources res = context.getResources();
    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    final boolean display_screen_name = NAME_DISPLAY_OPTION_SCREEN_NAME
            .equals(mPreferences.getString(PREFERENCE_KEY_NAME_DISPLAY_OPTION, NAME_DISPLAY_OPTION_BOTH));
    final boolean display_hires_profile_image = res.getBoolean(R.bool.hires_profile_image);
    switch (getTableId(uri)) {
    case URI_STATUSES: {
        if (!mPreferences.getBoolean(PREFERENCE_KEY_NOTIFICATION_ENABLE_HOME_TIMELINE, false))
            return;
        final String message = res.getQuantityString(R.plurals.Ntweets, mNewStatusesCount, mNewStatusesCount);
        final Intent delete_intent = new Intent(BROADCAST_NOTIFICATION_CLEARED);
        final Bundle delete_extras = new Bundle();
        delete_extras.putInt(INTENT_KEY_NOTIFICATION_ID, NOTIFICATION_ID_HOME_TIMELINE);
        delete_intent.putExtras(delete_extras);
        final Intent content_intent = new Intent(context, HomeActivity.class);
        content_intent.setAction(Intent.ACTION_MAIN);
        content_intent.addCategory(Intent.CATEGORY_LAUNCHER);
        final Bundle content_extras = new Bundle();
        content_extras.putInt(INTENT_KEY_INITIAL_TAB, HomeActivity.TAB_POSITION_HOME);
        content_intent.putExtras(content_extras);
        builder.setOnlyAlertOnce(true);
        final Notification notification = buildNotification(builder, res.getString(R.string.new_notifications),
                message, message, R.drawable.ic_stat_tweet, null, content_intent, delete_intent);
        mNotificationManager.notify(NOTIFICATION_ID_HOME_TIMELINE, notification);
        break;
    }
    case URI_MENTIONS: {
        if (!mPreferences.getBoolean(PREFERENCE_KEY_NOTIFICATION_ENABLE_MENTIONS, false))
            return;
        if (mNewMentionsCount > 1) {
            builder.setNumber(mNewMentionsCount);
        }
        final Intent delete_intent = new Intent(BROADCAST_NOTIFICATION_CLEARED);
        final Bundle delete_extras = new Bundle();
        delete_extras.putInt(INTENT_KEY_NOTIFICATION_ID, NOTIFICATION_ID_MENTIONS);
        delete_intent.putExtras(delete_extras);
        final Intent content_intent;
        final List<String> screen_names = new NoDuplicatesArrayList<String>();
        ContentValues notification_value = null;
        int notified_count = 0;
        for (final ContentValues value : values) {
            final String screen_name = value.getAsString(Statuses.SCREEN_NAME);
            if (!isFiltered(mDatabase, screen_name, value.getAsString(Statuses.SOURCE),
                    value.getAsString(Statuses.TEXT_PLAIN))) {
                if (notification_value == null) {
                    notification_value = value;
                }
                screen_names.add(screen_name);
                notified_count++;
            }
        }
        if (notified_count == 1) {
            final Uri.Builder uri_builder = new Uri.Builder();
            uri_builder.scheme(SCHEME_TWIDERE);
            uri_builder.authority(AUTHORITY_STATUS);
            uri_builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_ID,
                    notification_value.getAsString(Statuses.ACCOUNT_ID));
            uri_builder.appendQueryParameter(QUERY_PARAM_STATUS_ID,
                    notification_value.getAsString(Statuses.STATUS_ID));
            content_intent = new Intent(Intent.ACTION_VIEW, uri_builder.build());

        } else {
            content_intent = new Intent(context, HomeActivity.class);
            content_intent.setAction(Intent.ACTION_MAIN);
            content_intent.addCategory(Intent.CATEGORY_LAUNCHER);
            final Bundle content_extras = new Bundle();
            content_extras.putInt(INTENT_KEY_INITIAL_TAB, HomeActivity.TAB_POSITION_MENTIONS);
            content_intent.putExtras(content_extras);
        }
        if (notification_value == null)
            return;
        final String title;
        if (screen_names.size() > 1) {
            title = res.getString(R.string.notification_mention_multiple,
                    display_screen_name ? notification_value.getAsString(Statuses.SCREEN_NAME)
                            : notification_value.getAsString(Statuses.NAME),
                    screen_names.size() - 1);
        } else {
            title = res.getString(R.string.notification_mention,
                    display_screen_name ? notification_value.getAsString(Statuses.SCREEN_NAME)
                            : notification_value.getAsString(Statuses.NAME));
        }
        final String message = notification_value.getAsString(Statuses.TEXT_PLAIN);
        final String profile_image_url_string = notification_value.getAsString(Statuses.PROFILE_IMAGE_URL);
        final File profile_image_file = mProfileImageLoader.getCachedImageFile(
                display_hires_profile_image ? getBiggerTwitterProfileImage(profile_image_url_string)
                        : profile_image_url_string);
        final int w = res.getDimensionPixelSize(R.dimen.notification_large_icon_width);
        final int h = res.getDimensionPixelSize(R.dimen.notification_large_icon_height);
        builder.setLargeIcon(Bitmap.createScaledBitmap(profile_image_file != null && profile_image_file.isFile()
                ? BitmapFactory.decodeFile(profile_image_file.getPath())
                : BitmapFactory.decodeResource(res, R.drawable.ic_profile_image_default), w, h, true));
        final Notification notification = buildNotification(builder, title, title, message,
                R.drawable.ic_stat_mention, null, content_intent, delete_intent);
        mNotificationManager.notify(NOTIFICATION_ID_MENTIONS, notification);
        break;
    }
    case URI_DIRECT_MESSAGES_INBOX: {
        if (!mPreferences.getBoolean(PREFERENCE_KEY_NOTIFICATION_ENABLE_DIRECT_MESSAGES, false))
            return;
        if (mNewMessagesCount > 1) {
            builder.setNumber(mNewMessagesCount);
        }
        final List<String> screen_names = new NoDuplicatesArrayList<String>();
        final ContentValues notification_value = values[0];
        for (final ContentValues value : values) {
            screen_names.add(value.getAsString(DirectMessages.SENDER_SCREEN_NAME));
        }
        if (notification_value == null)
            return;
        final String title;
        if (screen_names.size() > 1) {
            title = res.getString(R.string.notification_direct_message_multiple,
                    display_screen_name ? notification_value.getAsString(DirectMessages.SENDER_SCREEN_NAME)
                            : notification_value.getAsString(DirectMessages.SENDER_NAME),
                    screen_names.size() - 1);
        } else {
            title = res.getString(R.string.notification_direct_message,
                    display_screen_name ? notification_value.getAsString(DirectMessages.SENDER_SCREEN_NAME)
                            : notification_value.getAsString(DirectMessages.SENDER_NAME));
        }
        final String message = notification_value.getAsString(DirectMessages.TEXT_PLAIN);
        final String profile_image_url_string = notification_value
                .getAsString(DirectMessages.SENDER_PROFILE_IMAGE_URL);
        final File profile_image_file = mProfileImageLoader.getCachedImageFile(
                display_hires_profile_image ? getBiggerTwitterProfileImage(profile_image_url_string)
                        : profile_image_url_string);
        final int w = res.getDimensionPixelSize(R.dimen.notification_large_icon_width);
        final int h = res.getDimensionPixelSize(R.dimen.notification_large_icon_height);
        builder.setLargeIcon(Bitmap.createScaledBitmap(profile_image_file != null && profile_image_file.isFile()
                ? BitmapFactory.decodeFile(profile_image_file.getPath())
                : BitmapFactory.decodeResource(res, R.drawable.ic_profile_image_default), w, h, true));
        final Intent delete_intent = new Intent(BROADCAST_NOTIFICATION_CLEARED);
        final Bundle delete_extras = new Bundle();
        delete_extras.putInt(INTENT_KEY_NOTIFICATION_ID, NOTIFICATION_ID_DIRECT_MESSAGES);
        delete_intent.putExtras(delete_extras);
        final Intent content_intent;
        if (values.length == 1) {
            final Uri.Builder uri_builder = new Uri.Builder();
            final long account_id = notification_value.getAsLong(DirectMessages.ACCOUNT_ID);
            final long conversation_id = notification_value.getAsLong(DirectMessages.SENDER_ID);
            uri_builder.scheme(SCHEME_TWIDERE);
            uri_builder.authority(AUTHORITY_DIRECT_MESSAGES_CONVERSATION);
            uri_builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_ID, String.valueOf(account_id));
            uri_builder.appendQueryParameter(QUERY_PARAM_CONVERSATION_ID, String.valueOf(conversation_id));
            content_intent = new Intent(Intent.ACTION_VIEW, uri_builder.build());
        } else {
            content_intent = new Intent(context, HomeActivity.class);
            content_intent.setAction(Intent.ACTION_MAIN);
            content_intent.addCategory(Intent.CATEGORY_LAUNCHER);
            final Bundle content_extras = new Bundle();
            content_extras.putInt(INTENT_KEY_INITIAL_TAB, HomeActivity.TAB_POSITION_MESSAGES);
            content_intent.putExtras(content_extras);
        }
        final Notification notification = buildNotification(builder, title, title, message,
                R.drawable.ic_stat_direct_message, null, content_intent, delete_intent);
        mNotificationManager.notify(NOTIFICATION_ID_DIRECT_MESSAGES, notification);
        break;
    }
    }
}

From source file:com.antew.redditinpictures.library.reddit.LoginResponse.java

@Override
public void processHttpResponse(Context context) {
    ContentResolver resolver = context.getContentResolver();

    // Delete old logins
    resolver.delete(RedditContract.Login.CONTENT_URI, null, null);

    RedditLoginResponse response = JsonDeserializer.deserialize(result.getJson(), RedditLoginResponse.class);

    if (response == null) {
        Ln.e("Error parsing Reddit login response");
        return;//from w ww.ja va 2 s  . c  o  m
    }

    // The username isn't sent back with the login response, so we have it passed
    // through from the login request
    String username = BundleUtil.getString(result.getExtraData(), RedditContract.Login.USERNAME, null);
    if (response.getLoginResponse() != null && response.getLoginResponse().getData() != null) {
        response.getLoginResponse().getData().setUsername(username);
    }

    ContentValues loginValues = response.getContentValues();
    Intent loginNotify = new Intent(Constants.Broadcast.BROADCAST_LOGIN_COMPLETE);
    loginNotify.putExtra(Constants.Extra.EXTRA_USERNAME, username);
    Integer loginSuccess = loginValues.getAsInteger(RedditContract.Login.SUCCESS);
    if (loginSuccess != null && loginSuccess == 1) {
        loginNotify.putExtra(Constants.Extra.EXTRA_SUCCESS, true);
        resolver.insert(RedditContract.Login.CONTENT_URI, loginValues);
    } else {
        loginNotify.putExtra(Constants.Extra.EXTRA_SUCCESS, false);
        loginNotify.putExtra(Constants.Extra.EXTRA_ERROR_MESSAGE,
                loginValues.getAsString(RedditContract.Login.ERROR_MESSAGE));
        loginNotify.putExtra(Constants.Extra.EXTRA_USERNAME, username);
    }

    LocalBroadcastManager.getInstance(context).sendBroadcast(loginNotify);
}

From source file:com.abcvoipsip.ui.favorites.FavAdapter.java

@Override
public void bindView(View view, Context context, Cursor cursor) {
    ContentValues cv = new ContentValues();
    DatabaseUtils.cursorRowToContentValues(cursor, cv);

    int type = ContactsWrapper.TYPE_CONTACT;
    if (cv.containsKey(ContactsWrapper.FIELD_TYPE)) {
        type = cv.getAsInteger(ContactsWrapper.FIELD_TYPE);
    }/*from  w w  w. j  a  v a  2s.  c o  m*/

    if (type == ContactsWrapper.TYPE_GROUP) {
        showViewForHeader(view, true);
        TextView tv = (TextView) view.findViewById(R.id.header_text);
        ImageView icon = (ImageView) view.findViewById(R.id.header_icon);
        PresenceStatusSpinner presSpinner = (PresenceStatusSpinner) view
                .findViewById(R.id.header_presence_spinner);

        tv.setText(cv.getAsString(SipProfile.FIELD_DISPLAY_NAME));
        icon.setImageResource(WizardUtils.getWizardIconRes(cv.getAsString(SipProfile.FIELD_WIZARD)));
        presSpinner.setProfileId(cv.getAsLong(BaseColumns._ID));

    } else {
        showViewForHeader(view, false);
        ContactsWrapper.getInstance().bindContactView(view, context, cursor);

    }
}

From source file:br.com.scalasoft.alvaro.weather.FetchWeatherTask.java

String[] convertContentValuesToUXFormat(Vector<ContentValues> cvv) {
    // return strings to keep UI functional for now
    String[] resultStrs = new String[cvv.size()];
    for (int i = 0; i < cvv.size(); i++) {
        ContentValues weatherValues = cvv.elementAt(i);
        String highAndLow = formatHighLows(weatherValues.getAsDouble(WeatherEntry.COLUMN_MAX_TEMP),
                weatherValues.getAsDouble(WeatherEntry.COLUMN_MIN_TEMP));
        resultStrs[i] = getReadableDateString(weatherValues.getAsLong(WeatherEntry.COLUMN_DATE)) + " - "
                + weatherValues.getAsString(WeatherContract.WeatherEntry.COLUMN_SHORT_DESC) + " - "
                + highAndLow;//from  w ww.  j a v a  2s  .co  m
    }
    return resultStrs;
}

From source file:com.example.joel.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./*ww w .  ja  va 2s . co m*/
 */
private String[] 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";

    // According to the video, this SHOULD be in a try-catch but that breaks other things...
    // This lesson is seriously messed up.
    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 = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

    Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());

    String[] resultStrs = new String[numDays];

    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);

        String highAndLow = formatHighLows(high, low);
        String day = getReadableDateString(dateTime);
        resultStrs[i] = day + " - " + description + " - " + highAndLow;
    }
    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()) {
                ContentValues resultValues = new ContentValues();
                DatabaseUtils.cursorRowToContentValues(weatherCursor, resultValues);
                Log.v(LOG_TAG, "Query succeeded! **********");
                for (String key : resultValues.keySet()) {
                    Log.v(LOG_TAG, key + ": " + resultValues.getAsString(key));
                }
            } else {
                Log.v(LOG_TAG, "Query failed! :( **********");
            }
        }
    }
    return resultStrs;
}

From source file:com.kwang.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.//from  w  w w  .  j  a  v  a  2 s .co m
 */
private String[] 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 = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

    // Get and insert the new weather information into the database
    Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());

    String[] resultStrs = new String[numDays];

    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);

        String highAndLow = formatHighLows(high, low);
        String day = getReadableDateString(dateTime);
        resultStrs[i] = day + " - " + description + " - " + highAndLow;
    }

    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()) {
                ContentValues resultValues = new ContentValues();
                DatabaseUtils.cursorRowToContentValues(weatherCursor, resultValues);
                Log.v(LOG_TAG, "Query succeeded! **********");
                for (String key : resultValues.keySet()) {
                    Log.v(LOG_TAG, key + ": " + resultValues.getAsString(key));
                }
            } else {
                Log.v(LOG_TAG, "Query failed! :( **********");
            }
        }
    }

    return resultStrs;
}