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.deliciousdroid.platform.ContactManager.java

/**
 * Add a list of status messages to the contacts provider.
 * /* w  ww .  j a v a2  s.c om*/
 * @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.snda.mymarket.providers.downloads.DownloadTask.java

/**
 * Executes the download in a separate thread
 *///from  w  w  w  . j a va  2  s .  co  m
public void run() {
    if (mInfo.mStatus != Downloads.STATUS_RUNNING) {
        mInfo.mStatus = Downloads.STATUS_RUNNING;
        ContentValues values = new ContentValues();
        values.put(Downloads.COLUMN_STATUS, mInfo.mStatus);
        mContext.getContentResolver().update(mInfo.getAllDownloadsUri(), values, null, null);
    } else {
        if (Constants.LOGV) {
            Log.v(Constants.TAG, "download status is: " + mInfo.mStatus);
        }
    }

    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    State state = new State(mInfo);
    HttpStack client = null;
    PowerManager.WakeLock wakeLock = null;
    int finalStatus = Downloads.STATUS_UNKNOWN_ERROR;

    try {
        PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);
        wakeLock.acquire();

        if (Constants.LOGV) {
            Log.v(Constants.TAG, "initiating download for " + mInfo.mUri);
        }

        if (Build.VERSION.SDK_INT >= 9) {
            client = new HurlStack();
        } else {
            // Prior to Gingerbread, HttpUrlConnection was unreliable.
            // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            client = new HttpClientStack(AndroidHttpClient.newInstance(userAgent()));
        }

        boolean finished = false;
        while (!finished) {
            Log.i(Constants.TAG, "Initiating request for download " + mInfo.mId);
            HttpGet request = new HttpGet(state.mRequestUri);
            try {
                executeDownload(state, client, request);
                finished = true;
            } catch (RetryDownload exc) {
                // fall through
            } finally {
                request.abort();
                request = null;
            }
        }

        if (Constants.LOGV) {
            Log.v(Constants.TAG, "download completed for " + mInfo.mUri);
        }
        finalizeDestinationFile(state);
        finalStatus = Downloads.STATUS_SUCCESS;
    } catch (StopRequest error) {
        // remove the cause before printing, in case it contains PII
        Log.w(Constants.TAG, "Aborting request for download " + mInfo.mId + ": " + error.getMessage());
        finalStatus = error.mFinalStatus;
        // fall through to finally block
    } catch (Throwable ex) { // sometimes the socket code throws unchecked
        // exceptions
        Log.w(Constants.TAG, "Exception for id " + mInfo.mId + ": " + ex);
        finalStatus = Downloads.STATUS_UNKNOWN_ERROR;
        // falls through to the code that reports an error
    } finally {
        mNotifer.notifyDownloadSpeed(mInfo.mId, 0);

        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
        if (client != null) {
            try {
                client.close();
                client = null;
            } catch (IOException e) {
                e.printStackTrace();
                finalStatus = Downloads.STATUS_UNKNOWN_ERROR;
            }
        }
        cleanupDestination(state, finalStatus);
        notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter, state.mGotData,
                state.mFilename, state.mNewUri, state.mMimeType);
        mInfo.cancelTask();
    }
}

From source file:danga.sunshine.async_task.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
 * @param lon             the longitude of the city
 * @return the row ID of the added location.
 *///  w  w  w .j  a v a2 s  . c om
public long addLocation(String locationSetting, String cityName, double lat, double lon) {

    // First, check if the location with this city name exists in the db
    long locationId;
    Cursor locationCursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI,
            new String[] { WeatherContract.LocationEntry._ID },
            WeatherContract.LocationEntry.COLUMN_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_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:com.whalesocks.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/*from   w  w  w.ja v  a2 s.com*/
 * @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
    long locationId = 0;

    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()) {
        //Location found
        int localIndex = locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID);
        locationId = locationCursor.getLong(localIndex);
    } 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_LAT, lat);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);

        Uri locationInsertUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI,
                locationValues);
        if (locationInsertUri != null) {
            // inserted correctly
            locationId = ContentUris.parseId(locationInsertUri);
        }
    }
    locationCursor.close();
    // If it exists, return the current ID
    // Otherwise, insert it using the content resolver and the base URI
    return locationId;
}

From source file:com.example.binht.thoitiet.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
 * @param lon             the longitude of the city
 * @return the row ID of the added location.
 *//*from   ww  w  . jav a 2s. com*/
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 locationId;

    // First, check if the location with this city name exists in the db
    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:com.seneca.android.senfitbeta.DbHelper.java

public void insertExercise(String aut, String des, String name, String ogName, String date, String cat,
        int id) {
    Log.d("INSERT EXDB", "Inserting exercise...");

    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();

    values.put(AUTHOR, aut);/*  w  w  w.j  ava 2  s . co  m*/
    values.put(DESCRIPTION, des);
    values.put(NAMETYPE, name);
    values.put(ORIGNALNAME, ogName);
    values.put(CREATIONDATE, date);
    values.put(CATEGORY, cat);
    values.put(EXERCISE_ID, id);

    long info = db.insert(EXERCISE_TABLE, null, values);
}

From source file:grytsenko.coworkers.web.Employee.java

/**
 * Obtains data about position for {@link ContentResolver}.
 * /*w  ww . ja  va 2s  . co  m*/
 * @return the set of values.
 */
public ContentValues getPosition() {
    ContentValues values = new ContentValues();
    values.put(Organization.TITLE, position);
    values.put(Organization.TYPE, Organization.TYPE_WORK);
    return values;
}

From source file:com.textuality.lifesaver2.Columns.java

public ContentValues jsonToContentValues(JSONObject j) {
    ContentValues cv = new ContentValues();
    for (int i = 0; i < mNames.length; i++) {
        switch (mTypes[i]) {
        case STRING:
            j2cvString(j, cv, mNames[i]);
            break;
        case INT:
            j2cvInt(j, cv, mNames[i]);// ww  w  . j av  a 2s . com
            break;
        case LONG:
            j2cvLong(j, cv, mNames[i]);
            break;
        case FLOAT:
            j2cvFloat(j, cv, mNames[i]);
            break;
        case DOUBLE:
            j2cvDouble(j, cv, mNames[i]);
            break;
        }
    }

    return cv;
}

From source file:mobisocial.socialkit.musubi.DbObj.java

/**
 * Prepares ContentValues that can be delivered to Musubi's Content Provider
 * for insertion into a SocialDb feed.//from  w  ww.ja  v a  2  s  .  co m
 */
public static ContentValues toContentValues(Uri feedUri, Long parentObjId, Obj obj) {
    ContentValues values = new ContentValues();
    values.put(DbObj.COL_TYPE, obj.getType());
    if (obj.getStringKey() != null) {
        values.put(DbObj.COL_STRING_KEY, obj.getStringKey());
    }
    if (obj.getJson() != null) {
        values.put(DbObj.COL_JSON, obj.getJson().toString());
    }
    if (obj.getIntKey() != null) {
        values.put(DbObj.COL_INT_KEY, obj.getIntKey());
    }
    if (obj.getRaw() != null) {
        values.put(DbObj.COL_RAW, obj.getRaw());
    }
    if (parentObjId != null) {
        values.put(DbObj.COL_PARENT_ID, parentObjId);
    }
    try {
        Long feedId = Long.parseLong(feedUri.getLastPathSegment());
        values.put(DbObj.COL_FEED_ID, feedId);
    } catch (Exception e) {
        throw new IllegalArgumentException("No feed id found for " + feedUri, e);
    }
    return values;
}

From source file:com.example.dhrumil.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//  ww  w .  j  a va  2s . 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) {
    long locationId;
    // First, check if the location with this city name exists in the db
    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;
}