Example usage for android.content ContentValues put

List of usage examples for android.content ContentValues put

Introduction

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

Prototype

public void put(String key, byte[] value) 

Source Link

Document

Adds a value to the set.

Usage

From source file:com.deliciousdroid.platform.ContactManager.java

/**
 * Add a list of status messages to the contacts provider.
 * /*from ww  w .  j  av  a 2s .c o  m*/
 * @param context the context to use
 * @param accountName the username of the logged in user
 * @param statuses the list of statuses to store
 */
@TargetApi(15)
public static void insertStreamStatuses(Context context, String username) {
    final ContentValues values = new ContentValues();
    final ContentResolver resolver = context.getContentResolver();
    final BatchOperation batchOperation = new BatchOperation(context, resolver);
    List<Long> currentContacts = lookupAllContacts(resolver);

    for (long id : currentContacts) {

        String friendUsername = lookupUsername(resolver, id);
        long watermark = lookupHighWatermark(resolver, id);
        long newWatermark = watermark;

        try {
            List<Status> statuses = DeliciousFeed.fetchFriendStatuses(friendUsername);

            for (Status status : statuses) {

                if (status.getTimeStamp().getTime() > watermark) {

                    if (status.getTimeStamp().getTime() > newWatermark)
                        newWatermark = status.getTimeStamp().getTime();

                    values.clear();
                    values.put(StreamItems.RAW_CONTACT_ID, id);
                    values.put(StreamItems.TEXT, status.getStatus());
                    values.put(StreamItems.TIMESTAMP, status.getTimeStamp().getTime());
                    values.put(StreamItems.ACCOUNT_NAME, username);
                    values.put(StreamItems.ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
                    values.put(StreamItems.RES_ICON, R.drawable.ic_main);
                    values.put(StreamItems.RES_PACKAGE, context.getPackageName());
                    values.put(StreamItems.RES_LABEL, R.string.label);

                    batchOperation.add(ContactOperations.newInsertCpo(StreamItems.CONTENT_URI, false)
                            .withValues(values).build());
                    // A sync adapter should batch operations on multiple contacts,
                    // because it will make a dramatic performance difference.
                    if (batchOperation.size() >= 50) {
                        batchOperation.execute();
                    }
                }
            }

            values.clear();
            values.put(RawContacts.SYNC1, Long.toString(newWatermark));
            batchOperation.add(ContactOperations.newUpdateCpo(RawContacts.CONTENT_URI, false).withValues(values)
                    .withSelection(RawContacts._ID + "=?", new String[] { Long.toString(id) }).build());

            batchOperation.execute();

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

From source file:com.riasayu.gosuke.sunshine.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// ww w  .jav  a 2 s . c o m
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */
public 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 locationRowId = -1;
    Cursor cursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI, null,
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[] { locationSetting },
            null);
    if (cursor.moveToFirst()) {
        locationRowId = cursor.getLong(cursor.getColumnIndex(WeatherContract.LocationEntry._ID));
    } else {
        ContentValues locationValues = new ContentValues();
        locationValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        Uri locationUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI,
                locationValues);
        locationRowId = ContentUris.parseId(locationUri);
    }
    return locationRowId;
}

From source file:edu.nd.darts.cimon.database.CimonDatabaseAdapter.java

/**
 * Insert new monitor into Monitor table, automatically generating monitor id.
 * /*from  ww w.  j ava 2  s.c o m*/
 * @param offsettime    time offset to apply to data table times to acquire time
 *                        from epoch, in milliseconds
 * @return    new monitor id
 * 
 * @see MonitorTable
 */
public synchronized int insertMonitor(long offsettime) {
    if (DebugLog.DEBUG)
        Log.d(TAG, "CimonDatabaseAdapter.insertMonitor - insert into Monitor table: time-" + offsettime);
    ContentValues values = new ContentValues();
    values.put(MonitorTable.COLUMN_TIME_OFFSET, offsettime);
    values.put(MonitorTable.COLUMN_ENDTIME, 0);

    long rowid = database.insert(MonitorTable.TABLE_MONITOR, null, values);
    if (rowid >= 0) {
        Uri uri = Uri.withAppendedPath(CimonContentProvider.MONITOR_URI, String.valueOf(rowid));
        context.getContentResolver().notifyChange(uri, null);
    }
    return (int) rowid;
}

From source file:com.openerp.addons.messages.MessageSyncHelper.java

private JSONArray updateMessageStatus(JSONObject msgReplies, BaseDBHelper db) {
    JSONArray updatedIds = new JSONArray();
    try {//  w w w.  j  a va  2 s .c  om
        for (int j = 0; j < msgReplies.getJSONArray("records").length(); j++) {
            JSONObject objRes = msgReplies.getJSONArray("records").getJSONObject(j);
            String message_id = objRes.getJSONArray("message_id").getString(0);
            String read = (objRes.getString("read").equals("true")) ? "false" : "true";
            String starred = objRes.getString("starred");
            ContentValues values = new ContentValues();
            values.put("starred", starred);
            values.put("to_read", read);
            if (db.write(db, values, Integer.parseInt(message_id), true)) {
                updatedIds.put(Integer.parseInt(message_id));
            }

        }
    } catch (Exception e) {
    }
    return updatedIds;
}

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 ww w. j  av  a  2 s .c o m*/
 * 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:name.zurell.kirk.apps.android.rhetolog.RhetologApplication.java

public void setSessionStartTime(Uri sessionToSet, long timestamp) {
    ContentValues values = new ContentValues(1);
    values.put(RhetologContract.SessionsColumns.STARTTIME, timestamp);
    getContentResolver().update(sessionToSet, values, null, null);
}

From source file:name.zurell.kirk.apps.android.rhetolog.RhetologApplication.java

public void setSessionEndTime(Uri sessionToSet, long timestamp) {
    ContentValues values = new ContentValues(1);
    values.put(RhetologContract.SessionsColumns.ENDTIME, timestamp);
    getContentResolver().update(sessionToSet, values, null, null);
}

From source file:com.udacity.sunshine.FetchWeatherTask.java

private long addLocation(String locationSetting, String cityName, double lat, double lon) {

    Log.v(LOG_TAG, "inserting " + cityName + ", with coord: " + lat + ", " + lon);

    String[] projection = { LocationEntry._ID }; // whichever column doesn't matter, but don't need to return all
    String[] selectionArgs = { locationSetting };
    String selection = LocationEntry.COLUMN_LOCATION_SETTING + " = ? ";
    // Check to see if location setting exists in db
    Cursor cursor = mContext.getContentResolver().query(LocationEntry.CONTENT_URI, projection, selection,
            selectionArgs, null);//w  ww . j av  a2 s .c  o m

    long locationRowId;

    if (cursor.moveToFirst()) {
        Log.v(LOG_TAG, "Found it in the database!");
        int locationIdIndex = cursor.getColumnIndex(LocationEntry._ID);
        locationRowId = cursor.getLong(locationIdIndex);
    } else {
        Log.v(LOG_TAG, "Didn't find it in the database, inserting now!");

        ContentValues locationValues = new ContentValues();
        locationValues.put(LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        locationValues.put(LocationEntry.COLUMN_CITY_NAME, cityName);
        locationValues.put(LocationEntry.COLUMN_COORD_LAT, lat);
        locationValues.put(LocationEntry.COLUMN_COORD_LONG, lon);

        Uri locationUri = mContext.getContentResolver().insert(LocationEntry.CONTENT_URI, locationValues);
        locationRowId = ContentUris.parseId(locationUri);
    }
    cursor.close();

    return locationRowId;
}

From source file:com.android.server.MaybeDatabaseHelper.java

public long setUrl(String packagename, String url) {
    Log.v(DBTAG, "packagename=" + packagename + " url=" + url);
    if (packagename == null || url == null) {
        return 0;
    }//  ww w.ja  v a2 s.c  om
    Log.v(DBTAG, "packagename=" + packagename + " url=" + url);
    if (rowExists(packagename)) {
        Log.v(DBTAG, "Row exists");
        listTableContents(); //TODO: test- remove in final code
        return 0;
    }
    Log.v(DBTAG, "Row does not exist");
    listTableContents();
    long ret;

    synchronized (sAppTableLock) {
        final ContentValues c = new ContentValues();
        c.put(PACKAGE_COL, packagename);
        c.put(URL_COL, url);
        ret = sDatabase.insert(APP_TABLE_NAME, URL_COL, c);
    }
    Log.v(DBTAG, "Database value inserted" + getAppDataFromDb(URL_COL, packagename));
    return ret;
}

From source file:edu.nd.darts.cimon.database.CimonDatabaseAdapter.java

/**
 * Insert new metric into Metrics table, or replace if the id already exist.
 * //from w w  w  .ja  v  a 2  s  . c om
 * @param id        id which identifies individual metric to insert
 * @param group     id of metric group this metric belongs to
 * @param metric    name of metric
 * @param units     units of metric values
 * @param max       maximum potential value
 * @return    rowid of inserted row, -1 on failure
 * 
 * @see MetricsTable
 */
public synchronized long insertOrReplaceMetrics(int id, int group, String metric, String units, float max) {
    if (DebugLog.DEBUG)
        Log.d(TAG, "CimonDatabaseAdapter.insertOrReplaceMetrics - insert into Metrics table: metric-" + metric);
    ContentValues values = new ContentValues();
    values.put(MetricsTable.COLUMN_ID, id);
    values.put(MetricsTable.COLUMN_INFO_ID, group);
    values.put(MetricsTable.COLUMN_METRIC, metric);
    values.put(MetricsTable.COLUMN_UNITS, units);
    values.put(MetricsTable.COLUMN_MAX, max);

    long rowid = database.replace(MetricsTable.TABLE_METRICS, null, values);
    if (rowid >= 0) {
        Uri uri = Uri.withAppendedPath(CimonContentProvider.METRICS_URI, String.valueOf(id));
        context.getContentResolver().notifyChange(uri, null);
    }
    return rowid;
}