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:net.eledge.android.toolkit.db.abstracts.Dao.java

private ContentValues mapToContentValues(E entity) {
    ContentValues values = new ContentValues();
    try {/*from   ww w .  j av a2 s  . c o m*/
        for (Field field : clazz.getFields()) {
            if (field.isAnnotationPresent(Column.class)) {
                final FieldType fieldType = FieldType.getType(field.getType());
                final String key = SQLBuilder.getFieldName(field);
                final String value = fieldType.toString(entity, field);
                values.put(key, value);
            }
        }
    } catch (IllegalArgumentException | IllegalAccessException e) {
        Log.e(this.getClass().getName(), e.getMessage(), e);
    }
    return values;
}

From source file:net.peterkuterna.android.apps.devoxxsched.service.CfpSyncService.java

@Override
protected void doSync(Intent intent) throws Exception {
    Log.d(TAG, "Start sync");

    Thread.sleep(5000);/*  w w  w.  j a  va  2  s .c o  m*/

    final Context context = this;

    final SharedPreferences settings = Prefs.get(context);
    final int localVersion = settings.getInt(DevoxxPrefs.CFP_LOCAL_VERSION, VERSION_NONE);

    final long startLocal = System.currentTimeMillis();
    final boolean localParse = localVersion < VERSION_CURRENT;
    Log.d(TAG, "found localVersion=" + localVersion + " and VERSION_CURRENT=" + VERSION_CURRENT);
    if (localParse) {
        // Parse values from local cache first
        mLocalExecutor.execute(R.xml.search_suggest, new SearchSuggestHandler());
        mLocalExecutor.execute(R.xml.rooms, new RoomsHandler());
        mLocalExecutor.execute(R.xml.tracks, new TracksHandler());
        mLocalExecutor.execute(R.xml.presentationtypes, new SessionTypesHandler());
        mLocalExecutor.execute(context, "cache-speakers.json", new SpeakersHandler());
        mLocalExecutor.execute(context, "cache-presentations.json", new SessionsHandler());
        mLocalExecutor.execute(context, "cache-schedule.json", new ScheduleHandler());

        mLocalExecutor.execute(context, "cache-parleys-presentations.json", new ParleysPresentationsHandler());

        // Save local parsed version
        settings.edit().putInt(DevoxxPrefs.CFP_LOCAL_VERSION, VERSION_CURRENT).commit();

        final ContentValues values = new ContentValues();
        values.put(Sessions.SESSION_NEW, 0);
        getContentResolver().update(Sessions.CONTENT_NEW_URI, values, null, null);
    }
    Log.d(TAG, "Local sync took " + (System.currentTimeMillis() - startLocal) + "ms");

    final CfpSyncManager syncManager = new CfpSyncManager(context);
    if (syncManager.shouldPerformRemoteSync(Intent.ACTION_SYNC.equals(intent.getAction()))) {
        Log.d(TAG, "Should perform remote sync");
        final long startRemote = System.currentTimeMillis();

        Editor prefsEditor = syncManager.hasRemoteContentChanged(mHttpClient);
        if (prefsEditor != null) {
            Log.d(TAG, "Remote content was changed");
            mRemoteExecutor.executeGet(SPEAKERS_URL, new SpeakersHandler());
            mRemoteExecutor.executeGet(PRESENTATIONS_URL, new SessionsHandler());
            mRemoteExecutor.executeGet(SCHEDULE_URL, new ScheduleHandler());
            prefsEditor.commit();
        }
        Log.d(TAG, "Remote sync took " + (System.currentTimeMillis() - startRemote) + "ms");
    } else {
        Log.d(TAG, "Should not perform remote sync");
    }

    final CfpDatabase database = new CfpDatabase(this);
    database.cleanupLinkTables();

    final NotifierManager notifierManager = new NotifierManager(this);
    notifierManager.notifyNewSessions();

    Log.d(TAG, "Sync finished");
}

From source file:edu.mit.mobile.android.livingpostcards.data.Card.java

public static boolean setCollaborative(ContentResolver cr, Uri card, boolean collaborative) {
    final ContentValues cv = new ContentValues();

    cv.put(Card.COL_PRIVACY, collaborative ? Card.PRIVACY_PUBLIC : Card.PRIVACY_PROTECTED);
    final int count = cr.update(card, cv, null, null);

    return count >= 1;
}

From source file:com.example.len.sunshinelessons1.FetchWeatherTask.java

/**
 * Helper method to handle insertion of a new location in the weather database.
 *
 * @param locationSetting The location string used to request updates from the server.
 * @param cityName A human-readable city name, e.g "Mountain View"
 * @param lat the latitude of the city//from  w  ww.j  a v  a2s.  co m
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */
long addLocation(String locationSetting, String cityName, double lat, double lon) {
    long locationId;

    Cursor locationCursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI,
            new String[] { WeatherContract.LocationEntry._ID },
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[] { locationSetting },
            null);

    if (locationCursor.moveToFirst()) {
        int locationIdIndex = locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID);
        locationId = locationCursor.getLong(locationIdIndex);
    } else {
        // Now that the content provider is set up, inserting rows of data is pretty simple.
        // First create a ContentValues object to hold the data you want to insert.
        ContentValues locationValues = new ContentValues();

        // Then add the data, along with the corresponding name of the data type,
        // so the content provider knows what kind of value is being inserted.
        locationValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);

        // Finally, insert location data into the database.
        Uri insertedUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI,
                locationValues);

        // The resulting URI contains the ID for the row.  Extract the locationId from the Uri.
        locationId = ContentUris.parseId(insertedUri);
    }

    locationCursor.close();
    // Wait, that worked?  Yes!
    return locationId;
}

From source file:de.tudarmstadt.dvs.myhealthassistant.myhealthhub.services.transformationmanager.database.LocalTransformationDBMS.java

public boolean addTraffic(String date, int trafficType, double xValue, double yValue) {

    ContentValues values = new ContentValues();
    values.put(LocalTransformationDB.COLUMN_DATE_TEXT, date);
    values.put(LocalTransformationDB.COLUMN_TYPE, trafficType);
    values.put(LocalTransformationDB.COLUMN_X_AXIS, xValue);
    values.put(LocalTransformationDB.COLUMN_Y_AXIS, yValue);
    long insertId = database.insert(LocalTransformationDB.TABLE_TRAFFIC_MON, null, values);
    if (insertId == -1) {
        Log.e(TAG, "addTraffic failed at:[" + date + "; type:" + trafficType + "; " + xValue + "; " + yValue
                + "]");
    }//from   ww w.  j  a  v a  2s  . c om
    return insertId != -1;
}

From source file:cn.code.notes.gtask.data.SqlNote.java

public SqlNote(Context context, long id) {
    mContext = context;/*from  ww w . j  ava 2  s. co m*/
    mContentResolver = context.getContentResolver();
    mIsCreate = false;
    loadFromCursor(id);
    mDataList = new ArrayList<SqlData>();
    if (mType == Notes.TYPE_NOTE)
        loadDataContent();
    mDiffNoteValues = new ContentValues();

}

From source file:com.nonobay.fana.udacityandroidproject1popularmovies.FetchMovieTask.java

/**
 * Take the String representing the complete movies in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 * <p/>//from w  w w  .  java  2s  .  c om
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.
 */
private void getMovieDataFromJson(String moviesJsonStr) throws JSONException {

    // Now we have a String representing the complete movie list in JSON Format.
    // Fortunately parsing is easy:  constructor takes the JSON string and converts it
    // into an Object hierarchy for us.

    /* example
    {
    "page": 1,
    "results": [
        {
            "adult": false,
                "backdrop_path": "/razvUuLkF7CX4XsLyj02ksC0ayy.jpg",
                "genre_ids": [
            80,
                    28,
                    53
            ],
            "id": 260346,
                "original_language": "en",
                "original_title": "Taken 3",
                "overview": "Ex-government operative Bryan Mills finds his life is shattered when he's falsely accused of a murder that hits close to home. As he's pursued by a savvy police inspector, Mills employs his particular set of skills to track the real killer and exact his unique brand of justice.",
                "release_date": "2015-01-09",
                "poster_path": "/c2SSjUVYawDUnQ92bmTqsZsPEiB.jpg",
                "popularity": 11.737899,
                "title": "Taken 3",
                "video": false,
                "vote_average": 6.2,
                "vote_count": 698
        }
    ],
    "total_pages": 11543,
    "total_results": 230847
    }*/

    // These are the names of the JSON objects that need to be extracted.
    final String JSON_PAGE = "page";
    final String JSON_PAGE_TOTAL = "total_pages";
    final String JSON_MOVIE_LIST = "results";
    final String JSON_MOVIE_TOTAL = "total_results";

    final String JSON_MOVIE_ID = "id";
    final String JSON_MOVIE_TITLE = "original_title";
    final String JSON_MOVIE_DATE = "release_date";
    final String JSON_MOVIE_POSTER = "poster_path";
    final String JSON_MOVIE_OVERVIEW = "overview";
    final String JSON_MOVIE_VOTE_AVERAGE = "vote_average";

    try {

        JSONObject moviesJson = new JSONObject(moviesJsonStr);

        JSONArray movieArray = moviesJson.getJSONArray(JSON_MOVIE_LIST);

        // Insert the new movie information into the database
        Vector<ContentValues> cVVector = new Vector<>(movieArray.length());

        // These are the values that will be collected.
        String releaseTime;
        long movieId;
        double vote_average;
        String overview;
        String original_title;
        String poster_path;

        for (int i = 0; i < movieArray.length(); i++) {

            // Get the JSON object representing the movie
            JSONObject eachMovie = movieArray.getJSONObject(i);

            movieId = eachMovie.getLong(JSON_MOVIE_ID);
            original_title = eachMovie.getString(JSON_MOVIE_TITLE);
            overview = eachMovie.getString(JSON_MOVIE_OVERVIEW);
            poster_path = eachMovie.getString(JSON_MOVIE_POSTER);
            vote_average = eachMovie.getDouble(JSON_MOVIE_VOTE_AVERAGE);
            releaseTime = eachMovie.getString(JSON_MOVIE_DATE);

            ContentValues movieValues = new ContentValues();
            movieValues.put(MovieContract.MovieEntry.COLUMN_MOVIE_ID, movieId);
            movieValues.put(MovieContract.MovieEntry.COLUMN_ORIGINAL_TITLE, original_title);
            movieValues.put(MovieContract.MovieEntry.COLUMN_POSTER_THUMBNAIL, poster_path);
            movieValues.put(MovieContract.MovieEntry.COLUMN_SYNOPSIS, overview);
            movieValues.put(MovieContract.MovieEntry.COLUMN_RELEASE_DATE, releaseTime);
            movieValues.put(MovieContract.MovieEntry.COLUMN_USER_RATING, vote_average);

            cVVector.add(movieValues);
        }

        // add to database
        if (cVVector.size() > 0) {
            // Student: call bulkInsert to add the weatherEntries to the database here
            mContext.getContentResolver().delete(MovieContract.MovieEntry.CONTENT_URI, null, null);
            mContext.getContentResolver().bulkInsert(MovieContract.MovieEntry.CONTENT_URI,
                    cVVector.toArray(new ContentValues[cVVector.size()]));
        }

    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
}

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

/**
 * Helper method to handle insertion of a new location in the weather database.
 *
 * @param locationSetting The location string used to request updates from the server.
 * @param cityName A human-readable city name, e.g "Mountain View"
 * @param lat the latitude of the city//from  ww w. j  av a 2s  .  c  om
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */
long addLocation(String locationSetting, String cityName, double lat, double lon) {
    // Students: First, check if the location with this city name exists in the db
    // If it exists, return the current ID
    // Otherwise, insert it using the content resolver and the base URI
    long rowId;
    final ContentResolver resolver = mContext.getContentResolver();
    Uri uri = Uri.parse(WeatherContract.BASE_CONTENT_URI + "/" + WeatherContract.PATH_LOCATION);
    String selectionArgs[] = { WeatherContract.LocationEntry.COLUMN_CITY_NAME };
    String selection = WeatherContract.LocationEntry.COLUMN_CITY_NAME + " =? ";

    //First, query database to check if this location already exists.
    Cursor cursor = resolver.query(uri, null, selection, new String[] { cityName }, null);

    if (cursor.moveToNext())
        return Long.parseLong(cursor.getString(cursor.getColumnIndex(WeatherContract.LocationEntry._ID)));
    else {
        ContentValues values = new ContentValues();
        values.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        values.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        values.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        values.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);
        //resolver.insert(uri, values);
        return Long.parseLong(resolver.insert(uri, values).getLastPathSegment());
    }
    // return -1;
}

From source file:eu.inmite.apps.smsjizdenka.service.UpdateService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent == null) {
        return;//from   w  ww  .  j  a va  2s .c om
    }
    final boolean force = intent.getBooleanExtra("force", false);
    try {
        Locale loc = Locale.getDefault();
        String lang = loc.getISO3Language(); // http://www.loc.gov/standards/iso639-2/php/code_list.php; T-values if present both T and B
        if (lang == null || lang.length() == 0) {
            lang = "";
        }

        int serverVersion = intent.getIntExtra("serverVersion", -1);
        boolean fromPush = serverVersion != -1;
        JSONObject versionJson = null;
        if (!fromPush) {
            versionJson = getVersion(true);
            serverVersion = versionJson.getInt("version");
        }
        int localVersion = Preferences.getInt(c, Preferences.DATA_VERSION, -1);
        final String localLanguage = Preferences.getString(c, Preferences.DATA_LANGUAGE, "");

        if (serverVersion <= localVersion && !force && lang.equals(localLanguage)
                && !LOCAL_DEFINITION_TESTING) {
            // don't update
            DebugLog.i("Nothing new, not updating");
            return;
        }

        // update but don't notify about it.
        boolean firstLaunchNoUpdate = ((localVersion == -1
                && getVersion(false).getInt("version") == serverVersion) || !lang.equals(localLanguage));

        if (!firstLaunchNoUpdate) {
            DebugLog.i("There are new definitions available!");
        }

        handleAuthorMessage(versionJson, lang, intent, fromPush);

        InputStream is = getIS(URL_TICKETS_ID);
        try {
            String json = readResult(is);

            JSONObject o = new JSONObject(json);
            JSONArray array = o.getJSONArray("tickets");

            final SQLiteDatabase db = DatabaseHelper.get(this).getWritableDatabase();
            for (int i = 0; i < array.length(); i++) {
                final JSONObject city = array.getJSONObject(i);
                try {

                    final ContentValues cv = new ContentValues();
                    cv.put(Cities._ID, city.getInt("id"));
                    cv.put(Cities.CITY, getStringLocValue(city, lang, "city"));
                    if (city.has("city_pubtran")) {
                        cv.put(Cities.CITY_PUBTRAN, city.getString("city_pubtran"));
                    }
                    cv.put(Cities.COUNTRY, city.getString("country"));
                    cv.put(Cities.CURRENCY, city.getString("currency"));
                    cv.put(Cities.DATE_FORMAT, city.getString("dateFormat"));
                    cv.put(Cities.IDENTIFICATION, city.getString("identification"));
                    cv.put(Cities.LAT, city.getDouble("lat"));
                    cv.put(Cities.LON, city.getDouble("lon"));
                    cv.put(Cities.NOTE, getStringLocValue(city, lang, "note"));
                    cv.put(Cities.NUMBER, city.getString("number"));
                    cv.put(Cities.P_DATE_FROM, city.getString("pDateFrom"));
                    cv.put(Cities.P_DATE_TO, city.getString("pDateTo"));
                    cv.put(Cities.P_HASH, city.getString("pHash"));
                    cv.put(Cities.PRICE, city.getString("price"));
                    cv.put(Cities.PRICE_NOTE, getStringLocValue(city, lang, "priceNote"));
                    cv.put(Cities.REQUEST, city.getString("request"));
                    cv.put(Cities.VALIDITY, city.getInt("validity"));
                    if (city.has("confirmReq")) {
                        cv.put(Cities.CONFIRM_REQ, city.getString("confirmReq"));
                    }
                    if (city.has("confirm")) {
                        cv.put(Cities.CONFIRM, city.getString("confirm"));
                    }

                    final JSONArray additionalNumbers = city.getJSONArray("additionalNumbers");
                    for (int j = 0; j < additionalNumbers.length() && j < 3; j++) {
                        cv.put("ADDITIONAL_NUMBER_" + (j + 1), additionalNumbers.getString(j));
                    }

                    db.beginTransaction();
                    int count = db.update(DatabaseHelper.CITY_TABLE_NAME, cv,
                            Cities._ID + " = " + cv.getAsInteger(Cities._ID), null);
                    if (count == 0) {
                        db.insert(DatabaseHelper.CITY_TABLE_NAME, null, cv);
                    }

                    db.setTransactionSuccessful();
                    getContentResolver().notifyChange(Cities.CONTENT_URI, null);
                } finally {
                    if (db.inTransaction()) {
                        db.endTransaction();
                    }
                }
            }
            Preferences.set(c, Preferences.DATA_VERSION, serverVersion);
            Preferences.set(c, Preferences.DATA_LANGUAGE, lang);
            if (!firstLaunchNoUpdate && !fromPush) {
                final int finalServerVersion = serverVersion;
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(UpdateService.this,
                                getString(R.string.cities_update_completed, finalServerVersion),
                                Toast.LENGTH_LONG).show();
                    }
                });
            }
            if (LOCAL_DEFINITION_TESTING) {
                DebugLog.w(
                        "Local definition testing - data updated from assets - must be removed in production!");
            }
        } finally {
            is.close();
        }
    } catch (IOException e) {
        DebugLog.e("IOException when calling update: " + e.getMessage(), e);
    } catch (JSONException e) {
        DebugLog.e("JSONException when calling update: " + e.getMessage(), e);
    }
}

From source file:mx.com.adolfogarcia.popularmovies.data.TestUtilities.java

/**
 * Returns the values of a row that may be inserted into the movie database.
 *
 * @return the values of a row that may be inserted into the movie database.
 *//*from w  w  w .j  av a2s.  c o  m*/
static ContentValues createMadMaxMovieReviewValues() {
    ContentValues testValues = new ContentValues();
    testValues.put(CachedMovieReviewEntry.COLUMN_MOVIE_API_ID, 76341);
    testValues.put(CachedMovieReviewEntry.COLUMN_API_ID, "55edd26792514106d600e380");
    testValues.put(CachedMovieReviewEntry.COLUMN_AUTHOR, "extoix");
    testValues.put(CachedMovieReviewEntry.COLUMN_CONTENT, "Awesome movie!");
    testValues.put(CachedMovieReviewEntry.COLUMN_URL, "http://j.mp/1hQIOdj");
    return testValues;
}