Example usage for android.content ContentValues get

List of usage examples for android.content ContentValues get

Introduction

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

Prototype

public Object get(String key) 

Source Link

Document

Gets a value.

Usage

From source file:com.openerp.orm.ORM.java

/**
 * Creates the record onserver.//from  ww w . j  a v a 2s.  c om
 * 
 * @param dbHelper
 *            the db helper
 * @param values
 *            the values
 * @return the int
 */
public int createRecordOnserver(BaseDBHelper dbHelper, ContentValues values) {
    String model = dbHelper.getModelName();
    int newId = 0;
    try {
        JSONObject arguments = new JSONObject();
        for (String key : values.keySet()) {
            arguments.put(key, values.get(key));
        }
        newId = oe_obj.createNew(model, arguments).getInt("result");
    } catch (Exception e) {
    }
    return newId;

}

From source file:no.java.schedule.provider.parsers.SessionsParser.java

/**
 * Parse a given session {@link org.json.JSONObject} into the given
 * {@link android.content.ContentValues} for insertion into {@link no.java.schedule.provider.SessionsContract.Sessions#CONTENT_URI}.
 *//*from w w  w  .  j  ava2s.co  m*/
private ContentValues parseSession(JSONObject session) throws JSONException {

    ContentValues contentValues = new ContentValues();

    contentValues.put(SessionsColumns.TITLE, session.optString(SessionJsonKeys.SESSIONTITLE, null));
    contentValues.put(SessionsColumns.ABSTRACT, session.optString(SessionJsonKeys.SESSIONABSTRACT, null));
    contentValues.put(SessionsColumns.ROOM, session.optString(SessionJsonKeys.ROOM, null));

    contentValues.put(SessionsColumns.TYPE,
            session.optString(SessionJsonKeys.SESSIONTYPE, SessionsContract.TYPE_PRESENTATION));

    contentValues.put(SessionsColumns.WEB_LINK, session.optString(SessionJsonKeys.FULLLINK, null));
    //contentValues.put(SessionsColumns.LINK_ALT, session.optString(SessionJsonKeys.MODERATORLINK, null));

    contentValues.put(SessionsColumns.STARRED, 0);

    JSONObject start = session.getJSONObject(SessionJsonKeys.START);
    JSONObject end = session.getJSONObject(SessionJsonKeys.END);
    contentValues.put(BlocksColumns.TIME_START, parseJSONDateToLong(start));
    contentValues.put(BlocksColumns.TIME_END, parseJSONDateToLong(end));

    final JSONArray trackJson = session.getJSONArray("labels");
    if (trackJson.length() > 0) {
        contentValues.put(TracksColumns.TRACK, trackJson.getJSONObject(0).optString("displayName", "Error..."));
    }

    //TODO level indication

    String speakernames = "";

    JSONArray speakers = session.getJSONArray(SessionJsonKeys.SESSIONSPEAKERS);
    for (int i = 0; i < speakers.length(); i++) {
        JSONObject speaker = speakers.getJSONObject(i);
        speakernames += (i > 0 ? ", " : "") + speaker.get(SessionJsonKeys.SPEAKER_NAME);
    }

    contentValues.put(SessionsColumns.SPEAKER_NAMES, speakernames);

    JSONArray labels = session.getJSONArray(SessionJsonKeys.TAGS); //TODO labels
    contentValues.put(SessionsColumns.TAGS, "tags  not implemented ..");

    // Build search index string
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(contentValues.get(SessionsColumns.TITLE));
    stringBuilder.append(" ");
    stringBuilder.append(contentValues.get(SessionsColumns.SPEAKER_NAMES));
    stringBuilder.append(" ");
    stringBuilder.append(contentValues.get(SessionsColumns.ABSTRACT));
    stringBuilder.append(" ");
    stringBuilder.append(contentValues.get(SessionsColumns.TAGS));

    contentValues.put(SearchColumns.INDEX_TEXT, stringBuilder.toString());

    return contentValues;
}

From source file:org.mariotaku.twidere.util.Utils.java

public static long getAsLong(final ContentValues values, final String key, final long def) {
    if (values == null || key == null)
        return def;
    final Object value = values.get(key);
    if (value == null)
        return def;
    return Long.valueOf(value.toString());
}

From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java

private void upsertDataIntoExistingDBTable(SQLiteDatabase db, String tableId,
        ArrayList<ColumnDefinition> orderedColumns, ContentValues cvValues, boolean shouldUpdate) {
    String rowId = null;/* w  w w. j  a v  a2s.co m*/
    String whereClause = null;
    boolean specifiesConflictType = cvValues.containsKey(DataTableColumns.CONFLICT_TYPE);
    boolean nullConflictType = specifiesConflictType && (cvValues.get(DataTableColumns.CONFLICT_TYPE) == null);
    String[] whereArgs = new String[specifiesConflictType ? (1 + (nullConflictType ? 0 : 1)) : 1];
    boolean update = false;

    if (cvValues.size() <= 0) {
        throw new IllegalArgumentException(t + ": No values to add into table " + tableId);
    }

    ContentValues cvDataTableVal = new ContentValues();
    cvDataTableVal.putAll(cvValues);

    if (cvDataTableVal.containsKey(DataTableColumns.ID)) {
        // The user specified a row id; we need to determine whether to
        // insert or update the record, or to reject the action because
        // there are either checkpoint records for this row id, or, if
        // a server conflict is associated with this row, that the
        // _conflict_type to update was not specified.
        //
        // i.e., the tuple (_id, _conflict_type) should be unique. If
        // we find that there are more than 0 or 1 records matching this
        // tuple, then we should reject the update request.
        //
        // TODO: perhaps we want to allow updates to the local conflict
        // row if there are no checkpoints on it? I.e., change the
        // tri-state conflict type to a pair of states (local / remote).
        // and all local changes are flagged local. Remote only exists
        // if the server is in conflict.

        rowId = cvDataTableVal.getAsString(DataTableColumns.ID);
        if (rowId == null) {
            throw new IllegalArgumentException(DataTableColumns.ID + ", if specified, cannot be null");
        }

        if (specifiesConflictType) {
            if (nullConflictType) {
                whereClause = DataTableColumns.ID + " = ?" + " AND " + DataTableColumns.CONFLICT_TYPE
                        + " IS NULL";
                whereArgs[0] = rowId;
            } else {
                whereClause = DataTableColumns.ID + " = ?" + " AND " + DataTableColumns.CONFLICT_TYPE + " = ?";
                whereArgs[0] = rowId;
                whereArgs[1] = cvValues.getAsString(DataTableColumns.CONFLICT_TYPE);
            }
        } else {
            whereClause = DataTableColumns.ID + " = ?";
            whereArgs[0] = rowId;
        }

        String sel = "SELECT * FROM " + tableId + " WHERE " + whereClause;
        String[] selArgs = whereArgs;
        Cursor cursor = rawQuery(db, sel, selArgs);

        // There must be only one row in the db for the update to work
        if (shouldUpdate) {
            if (cursor.getCount() == 1) {
                update = true;
            } else if (cursor.getCount() > 1) {
                throw new IllegalArgumentException(
                        t + ": row id " + rowId + " has more than 1 row in table " + tableId);
            }
        } else {
            if (cursor.getCount() > 0) {
                throw new IllegalArgumentException(
                        t + ": id " + rowId + " is already present in table " + tableId);
            }
        }

    } else {
        rowId = "uuid:" + UUID.randomUUID().toString();
    }

    // TODO: This is broken w.r.t. updates of partial fields
    // TODO: This is broken w.r.t. updates of partial fields
    // TODO: This is broken w.r.t. updates of partial fields
    // TODO: This is broken w.r.t. updates of partial fields

    if (!cvDataTableVal.containsKey(DataTableColumns.ID)) {
        cvDataTableVal.put(DataTableColumns.ID, rowId);
    }

    if (update) {
        if (!cvDataTableVal.containsKey(DataTableColumns.SYNC_STATE)
                || (cvDataTableVal.get(DataTableColumns.SYNC_STATE) == null)) {
            cvDataTableVal.put(DataTableColumns.SYNC_STATE, SyncState.changed.name());
        }

        if (cvDataTableVal.containsKey(DataTableColumns.LOCALE)
                && (cvDataTableVal.get(DataTableColumns.LOCALE) == null)) {
            cvDataTableVal.put(DataTableColumns.LOCALE, DataTableColumns.DEFAULT_LOCALE);
        }

        if (cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TYPE)
                && (cvDataTableVal.get(DataTableColumns.SAVEPOINT_TYPE) == null)) {
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_TYPE, SavepointTypeManipulator.complete());
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TIMESTAMP)
                || cvDataTableVal.get(DataTableColumns.SAVEPOINT_TIMESTAMP) == null) {
            String timeStamp = TableConstants.nanoSecondsFromMillis(System.currentTimeMillis());
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_TIMESTAMP, timeStamp);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_CREATOR)
                || (cvDataTableVal.get(DataTableColumns.SAVEPOINT_CREATOR) == null)) {
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_CREATOR, DataTableColumns.DEFAULT_SAVEPOINT_CREATOR);
        }
    } else {

        if (!cvDataTableVal.containsKey(DataTableColumns.ROW_ETAG)
                || cvDataTableVal.get(DataTableColumns.ROW_ETAG) == null) {
            cvDataTableVal.put(DataTableColumns.ROW_ETAG, DataTableColumns.DEFAULT_ROW_ETAG);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SYNC_STATE)
                || (cvDataTableVal.get(DataTableColumns.SYNC_STATE) == null)) {
            cvDataTableVal.put(DataTableColumns.SYNC_STATE, SyncState.new_row.name());
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.CONFLICT_TYPE)) {
            cvDataTableVal.putNull(DataTableColumns.CONFLICT_TYPE);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.FILTER_TYPE)
                || (cvDataTableVal.get(DataTableColumns.FILTER_TYPE) == null)) {
            cvDataTableVal.put(DataTableColumns.FILTER_TYPE, DataTableColumns.DEFAULT_FILTER_TYPE);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.FILTER_VALUE)
                || (cvDataTableVal.get(DataTableColumns.FILTER_VALUE) == null)) {
            cvDataTableVal.put(DataTableColumns.FILTER_VALUE, DataTableColumns.DEFAULT_FILTER_VALUE);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.FORM_ID)) {
            cvDataTableVal.putNull(DataTableColumns.FORM_ID);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.LOCALE)
                || (cvDataTableVal.get(DataTableColumns.LOCALE) == null)) {
            cvDataTableVal.put(DataTableColumns.LOCALE, DataTableColumns.DEFAULT_LOCALE);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TYPE)
                || (cvDataTableVal.get(DataTableColumns.SAVEPOINT_TYPE) == null)) {
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_TYPE, SavepointTypeManipulator.complete());
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TIMESTAMP)
                || cvDataTableVal.get(DataTableColumns.SAVEPOINT_TIMESTAMP) == null) {
            String timeStamp = TableConstants.nanoSecondsFromMillis(System.currentTimeMillis());
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_TIMESTAMP, timeStamp);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_CREATOR)
                || (cvDataTableVal.get(DataTableColumns.SAVEPOINT_CREATOR) == null)) {
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_CREATOR, DataTableColumns.DEFAULT_SAVEPOINT_CREATOR);
        }
    }

    cleanUpValuesMap(orderedColumns, cvDataTableVal);

    boolean dbWithinTransaction = db.inTransaction();
    try {
        if (!dbWithinTransaction) {
            db.beginTransaction();
        }

        if (update) {
            db.update(tableId, cvDataTableVal, whereClause, whereArgs);
        } else {
            db.insertOrThrow(tableId, null, cvDataTableVal);
        }

        if (!dbWithinTransaction) {
            db.setTransactionSuccessful();
        }
    } finally {
        if (!dbWithinTransaction) {
            db.endTransaction();
        }
    }

}

From source file:com.android.mail.browse.ConversationCursor.java

private Object getCachedValue(String uri, int columnIndex) {
    ContentValues uriMap = mCacheMap.get(uri);
    if (uriMap != null) {
        String columnName;//from  w w  w  . ja  va2 s  .c o m
        if (columnIndex == DELETED_COLUMN_INDEX) {
            columnName = DELETED_COLUMN;
        } else {
            columnName = mColumnNames[columnIndex];
        }
        return uriMap.get(columnName);
    }
    return null;
}

From source file:com.android.mail.browse.ConversationCursor.java

/**
 * Returns a Conversation object for the current position, or null if it has not yet been
 * cached./*ww w  . j a  v  a  2  s.  c o m*/
 *
 * This method will apply any cached column data to the result.
 *
 */
public Conversation getCachedConversation() {
    Conversation result = mUnderlyingCursor.getConversation();
    if (result == null) {
        return null;
    }

    // apply any cached values
    // but skip over any cached values that aren't part of the cursor projection
    final ContentValues values = mCacheMap.get(mUnderlyingCursor.getInnerUri());
    if (values != null) {
        final ContentValues queryableValues = new ContentValues();
        for (String key : values.keySet()) {
            if (!mColumnNameSet.contains(key)) {
                continue;
            }
            putInValues(queryableValues, key, values.get(key));
        }
        if (queryableValues.size() > 0) {
            // copy-on-write to help ensure the underlying cached Conversation is immutable
            // of course, any callers this method should also try not to modify them
            // overmuch...
            result = new Conversation(result);
            result.applyCachedValues(queryableValues);
        }
    }
    return result;
}

From source file:com.android.mail.browse.ConversationCursor.java

/**
 * Cache a column name/value pair for a given Uri
 * @param uriString the Uri for which the column name/value pair applies
 * @param columnName the column name/*ww w.ja  va2 s .c  om*/
 * @param value the value to be cached
 */
private void cacheValue(String uriString, String columnName, Object value) {
    // Calling this method off the UI thread will mess with ListView's reading of the cursor's
    // count
    if (offUiThread()) {
        LogUtils.e(LOG_TAG, new Error(), "cacheValue incorrectly being called from non-UI thread");
    }

    synchronized (mCacheMapLock) {
        // Get the map for our uri
        ContentValues map = mCacheMap.get(uriString);
        // Create one if necessary
        if (map == null) {
            map = new ContentValues();
            mCacheMap.put(uriString, map);
        }
        // If we're caching a deletion, add to our count
        if (columnName.equals(DELETED_COLUMN)) {
            final boolean state = (Boolean) value;
            final boolean hasValue = map.get(columnName) != null;
            if (state && !hasValue) {
                mDeletedCount++;
                if (DEBUG) {
                    LogUtils.i(LOG_TAG, "Deleted %s, incremented deleted count=%d", uriString, mDeletedCount);
                }
            } else if (!state && hasValue) {
                mDeletedCount--;
                map.remove(columnName);
                if (DEBUG) {
                    LogUtils.i(LOG_TAG, "Undeleted %s, decremented deleted count=%d", uriString, mDeletedCount);
                }
                return;
            } else if (!state) {
                // Trying to undelete, but it's not deleted; just return
                if (DEBUG) {
                    LogUtils.i(LOG_TAG, "Undeleted %s, IGNORING, deleted count=%d", uriString, mDeletedCount);
                }
                return;
            }
        }
        putInValues(map, columnName, value);
        map.put(UPDATE_TIME_COLUMN, System.currentTimeMillis());
        if (DEBUG && (!columnName.equals(DELETED_COLUMN))) {
            LogUtils.i(LOG_TAG, "Caching value for %s: %s", uriString, columnName);
        }
    }
}

From source file:com.tct.mail.browse.ConversationCursor.java

/**
 * Returns a Conversation object for the current position, or null if it has not yet been
 * cached.//  w  w  w .j av  a2  s  . c o  m
 *
 * This method will apply any cached column data to the result.
 *
 */
public Conversation getCachedConversation() {
    Conversation result = mUnderlyingCursor.getConversation();
    if (result == null) {
        return null;
    }

    // apply any cached values
    // but skip over any cached values that aren't part of the cursor projection
    // TS: zhaotianyong 2015-01-27 EMAIL BUGFIX-912291 MOD_S
    if (mUnderlyingCursor.getInnerUri() != null) {
        final ContentValues values = mCacheMap.get(mUnderlyingCursor.getInnerUri());
        if (values != null) {
            final ContentValues queryableValues = new ContentValues();
            for (String key : values.keySet()) {
                if (!mColumnNameSet.contains(key)) {
                    continue;
                }
                putInValues(queryableValues, key, values.get(key));
            }
            if (queryableValues.size() > 0) {
                // copy-on-write to help ensure the underlying cached Conversation is immutable
                // of course, any callers this method should also try not to modify them
                // overmuch...
                result = new Conversation(result);
                result.applyCachedValues(queryableValues);
            }
        }
    }
    // TS: zhaotianyong 2015-01-27 EMAIL BUGFIX-912291 MOD_E
    return result;
}

From source file:com.adkdevelopment.earthquakesurvival.data.syncadapter.SyncAdapter.java

/**
 * Raises a notification with a biggest earthquake with each sync
 *
 * @param notifyValues data with the biggest recent earthquake
 *///w  ww.ja va2  s  .c o  m
private void sendNotification(ContentValues notifyValues) {

    Context context = getContext();

    if (Utilities.getNotificationsPrefs(context) && !Utilities.checkForeground(context)) {

        //checking the last update and notify if it' the first of the day
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        String lastNotificationKey = context.getString(R.string.sharedprefs_key_lastnotification);
        long lastSync = prefs.getLong(lastNotificationKey, 0);

        if (System.currentTimeMillis() - lastSync >= DateUtils.DAY_IN_MILLIS) {
            Intent intent = new Intent(context, DetailActivity.class);

            double latitude = notifyValues.getAsDouble(EarthquakeColumns.LATITUDE);
            double longitude = notifyValues.getAsDouble(EarthquakeColumns.LONGITUDE);
            LatLng latLng = new LatLng(latitude, longitude);

            String distance = context.getString(R.string.earthquake_distance,
                    LocationUtils.getDistance(latLng, LocationUtils.getLocation(context)));

            String magnitude = context.getString(R.string.earthquake_magnitude,
                    notifyValues.getAsDouble(EarthquakeColumns.MAG));
            String date = Utilities.getRelativeDate(notifyValues.getAsLong(EarthquakeColumns.TIME));

            double depth = notifyValues.getAsDouble(EarthquakeColumns.DEPTH);

            intent.putExtra(Feature.MAGNITUDE, notifyValues.getAsDouble(EarthquakeColumns.MAG));
            intent.putExtra(Feature.PLACE, notifyValues.getAsString(EarthquakeColumns.PLACE));
            intent.putExtra(Feature.DATE, date);
            intent.putExtra(Feature.LINK, notifyValues.getAsString(EarthquakeColumns.URL));
            intent.putExtra(Feature.LATLNG, latLng);
            intent.putExtra(Feature.DISTANCE, distance);
            intent.putExtra(Feature.DEPTH, depth);
            intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

            PendingIntent pendingIntent = PendingIntent.getActivity(context, EarthquakeObject.NOTIFICATION_ID_1,
                    intent, PendingIntent.FLAG_UPDATE_CURRENT);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

            Bitmap largeIcon = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);

            builder.setDefaults(Notification.DEFAULT_ALL).setAutoCancel(true)
                    .setContentTitle(context.getString(R.string.earthquake_statistics_largest))
                    .setContentText(context.getString(R.string.earthquake_magnitude,
                            notifyValues.get(EarthquakeColumns.MAG)))
                    .setContentIntent(pendingIntent).setSmallIcon(R.drawable.ic_info_black_24dp)
                    .setLargeIcon(largeIcon).setTicker(context.getString(R.string.app_name))
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .bigText(notifyValues.get(EarthquakeColumns.PLACE).toString() + "\n" + magnitude
                                    + "\n" + context.getString(R.string.earthquake_depth, depth) + "\n"
                                    + distance + "\n" + date))
                    .setGroup(EarthquakeObject.NOTIFICATION_GROUP).setGroupSummary(true);

            NotificationManagerCompat managerCompat = NotificationManagerCompat.from(context);
            managerCompat.notify(EarthquakeObject.NOTIFICATION_ID_1, builder.build());

            //refreshing last sync
            boolean success = prefs.edit().putLong(lastNotificationKey, System.currentTimeMillis()).commit();
        }
    }
}

From source file:com.openerp.orm.ORM.java

/**
 * Write.//from   w  ww  .  j  av a2 s .c  o m
 * 
 * @param dbHelper
 *            the db helper
 * @param values
 *            the values
 * @param id
 *            the id
 * @param fromServer
 *            the from server
 * @return true, if successful
 */
public boolean write(BaseDBHelper dbHelper, ContentValues values, int id, boolean fromServer) {

    // Handling many2one records
    HashMap<String, Object> many2onecols = dbHelper.getMany2OneColumns();
    // Handling Many2Many Records
    HashMap<String, Object> many2manycols = dbHelper.getMany2ManyColumns();
    for (String key : many2manycols.keySet()) {
        try {

            JSONArray m2mArray = new JSONArray(values.getAsString(key));
            Many2Many m2m = (Many2Many) many2manycols.get(key);
            updateM2MRecords(values.getAsString("id"), m2mArray, key, dbHelper, m2m, values);
        } catch (Exception e) {

        }
        values.remove(key);
    }
    // Handling many2one records. [id, "name"] to id
    for (String key : many2onecols.keySet()) {
        try {
            String tempVals = values.getAsString(key);
            if (!tempVals.equals("false")) {
                JSONArray m2oArray = new JSONArray(values.getAsString(key));
                int m2oid = m2oArray.getInt(0);
                values.put(key, m2oid);
            } else {
                values.put(key, "false");
            }
        } catch (Exception e) {
        }
    }

    boolean flag = false;
    SQLiteDatabase db = getWritableDatabase();
    try {
        if (OpenERPServerConnection.isNetworkAvailable(context)) {
            String table = modelToTable(dbHelper.getModelName());
            try {

                JSONObject arguments = new JSONObject();
                for (String key : values.keySet()) {
                    try {
                        int keyid = Integer.parseInt(values.getAsString(key));
                        arguments.put(key, keyid);
                    } catch (Exception e) {
                        String temp = values.getAsString(key);
                        if (temp.equals("true") || temp.equals("false")) {
                            arguments.put(key, ((temp.equals("true")) ? true : false));
                        } else {

                            arguments.put(key, values.get(key).toString());

                        }
                    }

                }
                if (fromServer) {
                    int res = db.update(table, values, "id = " + id, null);
                    flag = true;
                } else {

                    if (oe_obj.updateValues(dbHelper.getModelName(), arguments, id)) {
                        int res = db.update(table, values, "id = " + id, null);
                        flag = true;
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                flag = false;
            }

        } else {
            Toast.makeText(context, "Unable to Connect server ! Please Try again Later. ", Toast.LENGTH_LONG)
                    .show();
            flag = false;
        }
    } catch (Exception e) {
    }
    db.close();
    return flag;
}