Example usage for android.content ContentValues ContentValues

List of usage examples for android.content ContentValues ContentValues

Introduction

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

Prototype

public ContentValues() 

Source Link

Document

Creates an empty set of values using the default initial size

Usage

From source file:com.almarsoft.GroundhogReader.lib.DBUtils.java

public static void updateStarredThread(boolean starred, String clean_subject, int groupid, Context context) {
    DBHelper db = new DBHelper(context);
    SQLiteDatabase dbWrite = db.getWritableDatabase();

    clean_subject = clean_subject.replace("'", "''");

    String query;//  w ww  .  ja  va2s  .com

    if (starred == false) {
        query = "DELETE FROM starred_threads WHERE subscribed_group_id=" + groupid + " AND clean_subject="
                + esc(clean_subject);
        dbWrite.execSQL(query);
    } else {
        // Check that it's not already on the table
        query = "SELECT _ID FROM starred_threads WHERE subscribed_group_id=" + groupid + " AND clean_subject="
                + esc(clean_subject);
        Cursor c = dbWrite.rawQuery(query, null);

        if (c.getCount() == 0) {
            ContentValues cv = new ContentValues();
            cv.put("subscribed_group_id", groupid);
            cv.put("clean_subject", clean_subject);
            dbWrite.insert("starred_threads", null, cv);
        }
        c.close();
    }
    dbWrite.close();
    db.close();
}

From source file:com.example.diego.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/>// ww  w.  j  a va  2s  .c  o  m
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.
 */
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);

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

    ContentValues[] contentValuesToBulkInsert = new ContentValues[cVVector.size()];
    cVVector.toArray(contentValuesToBulkInsert);
    mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, contentValuesToBulkInsert);

    return resultStrs;
}

From source file:itreverie.weatherapp.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  av a 2 s  . c om
 */
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 = addLocation(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(WeatherContract.WeatherEntry.COLUMN_LOC_KEY, locationID);
        weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DATETEXT,
                WeatherContract.getDbDateString(new Date(dateTime * 1000L)));
        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);

    }
    if (cVVector.size() > 0) {
        //Converting a vector into an array
        ContentValues[] cvArray = new ContentValues[cVVector.size()];
        cVVector.toArray(cvArray);
        mContext.getContentResolver().bulkInsert(WeatherContract.WeatherEntry.CONTENT_URI, cvArray);
        //int rowsInserted =
        //        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(
                WeatherContract.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! :( **********");
        }
        }
        */
    }
}

From source file:com.example.mihai.inforoute.app.FetchWeatherTask.java

private void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException {

    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 {/*from www. j a  v a2s  .co  m*/
        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());

        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);
            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:com.stockita.popularmovie.utility.Utilities.java

/**
 * This is the method that will do the parsing and bulk inserting to tables,
 * MovieEntry, GenreEntry.//from   w w w  . ja v a  2s .  c o  m
 *
 */
public static void parseFeed(final Context context, String dataFetch, String key, String sortGroup) {

    // Instantiate the Content Resolver.
    sContentResolver = context.getContentResolver();

    // Timestamp.
    sCurrentTime = System.currentTimeMillis();

    // A container for MovieEntry for bulk insert
    ArrayList<ContentValues> lValuesMovieEntry = new ArrayList<>();

    // Lets rock n roll.
    try {

        // String to the root of JSONObject, the argument s is a String in JSON format.
        JSONObject rootObject = new JSONObject(dataFetch);

        // Call the rootObjet and get the key assign to String variable
        String rootObj = rootObject.get("results").toString();

        // Now the rootObj has the value of "result" which is a JSON Array
        // then assign it as argument into JSONArray object
        JSONArray ar = new JSONArray(rootObj);
        final int arSize = ar.length();

        // Iterate for each element in the JSONArray
        for (int i = 0; i < arSize; i++) {

            // Convert each element in ar into JSONOject
            // and pass the argument [i] which [i] is the index of each element.
            JSONObject obj = ar.getJSONObject(i);

            // Add Temp variable so we pass it to parseGenre() argument later.
            String movieIdHolder = obj.getString("id");

            // For MovieEntry
            ContentValues contentMovieValues = new ContentValues();
            contentMovieValues.put(ContractMovies.MovieEntry.COLUMN_BACKDROP_PATH,
                    obj.getString("backdrop_path"));
            contentMovieValues.put(ContractMovies.MovieEntry.COLUMN_MOVIE_ID, String.valueOf(movieIdHolder));
            contentMovieValues.put(ContractMovies.MovieEntry.COLUMN_ORIGINAL_LANGUAGE,
                    obj.getString("original_language"));
            contentMovieValues.put(ContractMovies.MovieEntry.COLUMN_MOVIE_TITLE,
                    obj.getString("original_title"));
            contentMovieValues.put(ContractMovies.MovieEntry.COLUMN_OVERVIEW, obj.getString("overview"));
            contentMovieValues.put(ContractMovies.MovieEntry.COLUMN_RELEASE_DATE,
                    obj.getString("release_date"));
            contentMovieValues.put(ContractMovies.MovieEntry.COLUMN_POSTER_PATH, obj.getString("poster_path"));
            contentMovieValues.put(ContractMovies.MovieEntry.COLUMN_POPULARITY, obj.getInt("popularity"));
            contentMovieValues.put(ContractMovies.MovieEntry.COLUMN_AVERAGE_VOTE,
                    obj.getDouble("vote_average"));
            contentMovieValues.put(ContractMovies.MovieEntry.COLUMN_VOTE_COUNT, obj.getInt("vote_count"));
            contentMovieValues.put(ContractMovies.MovieEntry.COLUMN_POSTING_TIME, sCurrentTime);
            contentMovieValues.put(ContractMovies.MovieEntry.COLUMN_SORT_GROUP, sortGroup);

            // Pack the object contentMovieValues into ArrayList<ContentValues> lValuesMovieEntry
            lValuesMovieEntry.add(contentMovieValues);

            // Begin of GenreEntry insert.
            // for extract sub array/field genre_ids
            JSONArray genre = obj.getJSONArray("genre_ids");
            parseGenre(context, movieIdHolder, genre, sCurrentTime, sortGroup);

        } // end for loop

        // MovieEntry
        // Bulk insert for MovieEntry.
        try {
            // Bulk insert
            ContentValues[] lInsertData = new ContentValues[lValuesMovieEntry.size()];
            lValuesMovieEntry.toArray(lInsertData);
            int lInsertedData = context.getContentResolver().bulkInsert(ContractMovies.MovieEntry.CONTENT_URI,
                    lInsertData);

        } catch (Exception e) {
            Log.e(LOG_TAG, e.toString());
        }

        // Store the current time millis in SharedPreference so we can use it
        // the next time.
        setTimeStamp(context, key, sCurrentTime);

    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:android.provider.Checkin.java

/**
 * Helper function to report a crash./*from   ww  w . j a va 2 s.  c o m*/
 *
 * @param resolver from {@link android.content.Context#getContentResolver}
 * @param crash data from {@link android.server.data.CrashData}
 * @return URI of the crash report that was added
 */
static public Uri reportCrash(ContentResolver resolver, byte[] crash) {
    try {
        // If we are in a situation where crash reports fail (such as a full disk),
        // it's important that we don't get into a loop trying to report failures.
        // So discard all crash reports for a few seconds after reporting fails.
        long realtime = SystemClock.elapsedRealtime();
        if (realtime - sLastCrashFailureRealtime < MIN_CRASH_FAILURE_RETRY) {
            Log.e(TAG, "Crash logging skipped, too soon after logging failure");
            return null;
        }

        // HACK: we don't support BLOB values, so base64 encode it.
        byte[] encoded = Base64.encodeBase64(crash);
        ContentValues values = new ContentValues();
        values.put(Crashes.DATA, new String(encoded));
        Uri uri = resolver.insert(Crashes.CONTENT_URI, values);
        if (uri == null) {
            Log.e(TAG, "Error reporting crash");
            sLastCrashFailureRealtime = SystemClock.elapsedRealtime();
        }
        return uri;
    } catch (Throwable t) {
        // To avoid an infinite crash-reporting loop, swallow all errors and exceptions.
        Log.e(TAG, "Error reporting crash: " + t);
        sLastCrashFailureRealtime = SystemClock.elapsedRealtime();
        return null;
    }
}