Java 类android.content.ContentValues 实例源码

项目:Udhari    文件:TxProvider.java   
@Nullable
@Override
public Uri insert(Uri uri, ContentValues values) {
    final SQLiteDatabase db = mCardsDBHelper.getWritableDatabase();

    Uri returnUri = null;
    int match = sUriMatcher.match(uri);
    switch (match) {
        case TRANSACTIONS: // Since insert and query all has same url
            long transactionId = db.insert(DatabaseContract.TABLE_TRANSACTIONS, null, values);
            if (transactionId > 0) {
                returnUri = ContentUris.withAppendedId(DatabaseContract.CONTENT_URI, transactionId);
                getContext().getContentResolver().notifyChange(uri, null);
            } else {
                throw new SQLException("Can't create ID");
            }
            break;
        default:
            throw new UnsupportedOperationException("This URI is not supported");
    }
    return returnUri;
}
项目:springreplugin    文件:PluginProviderClient.java   
/**
 * 调用插件里的Provider
 *
 * @see android.content.ContentResolver#bulkInsert(Uri, ContentValues[])
 */
public static int bulkInsert(Context c, Uri uri, ContentValues[] values) {
    if (c == null) {
        return 0;
    }

    if (!RePluginFramework.mHostInitialized) {
        return c.getContentResolver().bulkInsert(uri, values);
    }

    try {
        Object obj = ProxyRePluginProviderClientVar.bulkInsert.call(null, c, uri, values);
        if (obj != null) {
            return (Integer) obj;
        }
    } catch (Exception e) {
        if (LogDebug.LOG) {
            e.printStackTrace();
        }
    }

    return -1;
}
项目:ubiquitous    文件:TestUtilities.java   
/**
 * This method iterates through a set of expected values and makes various assertions that
 * will pass if our app is functioning properly.
 *
 * @param error          Message when an error occurs
 * @param valueCursor    The Cursor containing the actual values received from an arbitrary query
 * @param expectedValues The values we expect to receive in valueCursor
 */
static void validateCurrentRecord(String error, Cursor valueCursor, ContentValues expectedValues) {
    Set<Map.Entry<String, Object>> valueSet = expectedValues.valueSet();

    for (Map.Entry<String, Object> entry : valueSet) {
        String columnName = entry.getKey();
        int index = valueCursor.getColumnIndex(columnName);

        /* Test to see if the column is contained within the cursor */
        String columnNotFoundError = "Column '" + columnName + "' not found. " + error;
        assertFalse(columnNotFoundError, index == -1);

        /* Test to see if the expected value equals the actual value (from the Cursor) */
        String expectedValue = entry.getValue().toString();
        String actualValue = valueCursor.getString(index);

        String valuesDontMatchError = "Actual value '" + actualValue
                + "' did not match the expected value '" + expectedValue + "'. "
                + error;

        assertEquals(valuesDontMatchError,
                expectedValue,
                actualValue);
    }
}
项目:OpenHomeAnalysis    文件:OhaEnergyUseProvider.java   
@Override
public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
    SQLiteDatabase sqLiteDatabase = this.ohaSQLHelper.getWritableDatabase();
    switch (sUriMatcher.match(uri)) {
        case CODE_ENERGY_USER_LOG:
            return bulkInsertEnergyUseLogs(uri, values, sqLiteDatabase);
        default:
            throw new UnsupportedOperationException("Unknown uri: " + uri);
    }
}
项目:Cable-Android    文件:AttachmentDatabase.java   
@VisibleForTesting
protected void updateAttachmentThumbnail(MasterSecret masterSecret, AttachmentId attachmentId, InputStream in, float aspectRatio)
    throws MmsException
{
  Log.w(TAG, "updating part thumbnail for #" + attachmentId);

  Pair<File, Long> thumbnailFile = setAttachmentData(masterSecret, in);

  SQLiteDatabase database = databaseHelper.getWritableDatabase();
  ContentValues  values   = new ContentValues(2);

  values.put(THUMBNAIL, thumbnailFile.first.getAbsolutePath());
  values.put(THUMBNAIL_ASPECT_RATIO, aspectRatio);

  database.update(TABLE_NAME, values, PART_ID_WHERE, attachmentId.toStrings());

  Cursor cursor = database.query(TABLE_NAME, new String[] {MMS_ID}, PART_ID_WHERE, attachmentId.toStrings(), null, null, null);

  try {
    if (cursor != null && cursor.moveToFirst()) {
      notifyConversationListeners(DatabaseFactory.getMmsDatabase(context).getThreadIdForMessage(cursor.getLong(cursor.getColumnIndexOrThrow(MMS_ID))));
    }
  } finally {
    if (cursor != null) cursor.close();
  }
}
项目:LucaHome-AndroidApplication    文件:DatabaseMenuList.java   
public boolean Update(@NonNull LucaMenu updateEntry) throws SQLException {
    ContentValues contentValues = new ContentValues();

    contentValues.put(KEY_ROW_ID, updateEntry.GetId());
    contentValues.put(KEY_WEEKDAY, updateEntry.GetWeekday().GetEnglishDay());
    contentValues.put(KEY_DAY, String.valueOf(updateEntry.GetDate().DayOfMonth()));
    contentValues.put(KEY_MONTH, String.valueOf(updateEntry.GetDate().Month()));
    contentValues.put(KEY_YEAR, String.valueOf(updateEntry.GetDate().Year()));
    contentValues.put(KEY_TITLE, updateEntry.GetTitle());
    contentValues.put(KEY_DESCRIPTION, updateEntry.GetDescription());
    contentValues.put(KEY_IS_ON_SERVER, String.valueOf(updateEntry.GetIsOnServer()));
    contentValues.put(KEY_SERVER_ACTION, updateEntry.GetServerDbAction().toString());

    _database.update(DATABASE_TABLE, contentValues, KEY_ROW_ID + "=" + updateEntry.GetId(), null);

    return true;
}
项目:GiphyImageResultsPreview    文件:Helper.java   
public static Uri getImageContentUri(Context context, File imageFile) {
    String filePath = imageFile.getAbsolutePath();
    Cursor cursor = context.getContentResolver().query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            new String[]{MediaStore.Images.Media._ID},
            MediaStore.Images.Media.DATA + "=? ",
            new String[]{filePath}, null);
    if (cursor != null && cursor.moveToFirst()) {
        int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
        cursor.close();
        return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + id);
    } else {
        if (imageFile.exists()) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, filePath);
            return context.getContentResolver().insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        } else {
            return null;
        }
    }
}
项目:unity-obb-downloader    文件:DownloadsDB.java   
/**
 * This function will add a new file to the database if it does not exist.
 *
 * @param di DownloadInfo that we wish to store
 * @return the row id of the record to be updated/inserted, or -1
 */
public boolean updateDownload(DownloadInfo di) {
    ContentValues cv = new ContentValues();
    cv.put(DownloadColumns.INDEX, di.mIndex);
    cv.put(DownloadColumns.FILENAME, di.mFileName);
    cv.put(DownloadColumns.URI, di.mUri);
    cv.put(DownloadColumns.ETAG, di.mETag);
    cv.put(DownloadColumns.TOTALBYTES, di.mTotalBytes);
    cv.put(DownloadColumns.CURRENTBYTES, di.mCurrentBytes);
    cv.put(DownloadColumns.LASTMOD, di.mLastMod);
    cv.put(DownloadColumns.STATUS, di.mStatus);
    cv.put(DownloadColumns.CONTROL, di.mControl);
    cv.put(DownloadColumns.NUM_FAILED, di.mNumFailed);
    cv.put(DownloadColumns.RETRY_AFTER, di.mRetryAfter);
    cv.put(DownloadColumns.REDIRECT_COUNT, di.mRedirectCount);
    return updateDownload(di, cv);
}
项目:Todule-android    文件:ToduleProvider.java   
public Uri insert(Uri uri, ContentValues values){
    db = tOpenHelper.getWritableDatabase();
    long id;
    switch(sUriMatcher.match(uri)){
        case ENTRY_LIST:
            id = db.insert(TodoEntry.TABLE_NAME, null, values);
            break;
        case LABEL_LIST:
            id = db.insert(TodoLabel.TABLE_NAME, null, values);
            break;
        case NOTIFICATION_LIST:
            id = db.insert(TodoNotification.TABLE_NAME, null, values);
            break;
        default:
            throw new IllegalArgumentException("Unsupported URI for insertion: " + uri);
    }
    Uri itemUri = ContentUris.withAppendedId(uri, id);
    getContext().getContentResolver().notifyChange(itemUri, null);
    return itemUri;
}
项目:pets    文件:PetProvider.java   
/**
 * ********** UPDATE ***********
 *
 * @param uri
 * @param values
 * @param selection
 * @param selectionArgs
 * @return
 */
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues values,
                  @Nullable String selection, @Nullable String[] selectionArgs) {

    final int match = sUriMathcer.match(uri);
    switch (match) {
        case PETS:
            return updatePet(uri, values, selection, selectionArgs);
        case PETS_ID:
            // For PET_ID extract the pet ID from the URI
            String id = String.valueOf(ContentUris.parseId(uri));
            selection = PetEntry._ID + "=?";
            selectionArgs = new String[]{id};
            return updatePet(uri, values, selection, selectionArgs);
        default:
            throw new IllegalArgumentException("Update is not supported for " + uri);
    }
}
项目:ChatKeyboard-master    文件:EmoticonDBHelper.java   
public synchronized long insertEmoticonBeans(ContentValues[] values) {
    SQLiteDatabase db = mOpenDbHelper.getWritableDatabase();
    db.beginTransaction();
    int insertSuccessCount = values.length;
    try {
        for (ContentValues cv : values) {
            if (db.insert(TABLE_NAME_EMOTICONS, null, cv) < 0) {
                insertSuccessCount--;
            }
        }
        db.setTransactionSuccessful();
    } catch (Exception e) {
        Log.e("Keyboard", "insert error", e);
    }  finally {
        db.endTransaction();
    }
    return insertSuccessCount;
}
项目:GitHub    文件:HostBean.java   
@Override
public ContentValues getValues() {
    ContentValues values = new ContentValues();

    values.put(HostDatabase.FIELD_HOST_NICKNAME, nickname);
    values.put(HostDatabase.FIELD_HOST_PROTOCOL, protocol);
    values.put(HostDatabase.FIELD_HOST_USERNAME, username);
    values.put(HostDatabase.FIELD_HOST_HOSTNAME, hostname);
    values.put(HostDatabase.FIELD_HOST_PORT, port);
    values.put(HostDatabase.FIELD_HOST_LASTCONNECT, lastConnect);
    values.put(HostDatabase.FIELD_HOST_COLOR, color);
    values.put(HostDatabase.FIELD_HOST_USEKEYS, Boolean.toString(useKeys));
    values.put(HostDatabase.FIELD_HOST_USEAUTHAGENT, useAuthAgent);
    values.put(HostDatabase.FIELD_HOST_POSTLOGIN, postLogin);
    values.put(HostDatabase.FIELD_HOST_PUBKEYID, pubkeyId);
    values.put(HostDatabase.FIELD_HOST_WANTSESSION, Boolean.toString(wantSession));
    values.put(HostDatabase.FIELD_HOST_DELKEY, delKey);
    values.put(HostDatabase.FIELD_HOST_FONTSIZE, fontSize);
    values.put(HostDatabase.FIELD_HOST_COMPRESSION, Boolean.toString(compression));
    values.put(HostDatabase.FIELD_HOST_ENCODING, encoding);
    values.put(HostDatabase.FIELD_HOST_STAYCONNECTED, Boolean.toString(stayConnected));
    values.put(HostDatabase.FIELD_HOST_QUICKDISCONNECT, Boolean.toString(quickDisconnect));

    return values;
}
项目:Sanxing    文件:TimeLeftRepo.java   
public void update(TimeLeft timeLeft) {

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

        values.put(TimeLeft.KEY_TITLE,timeLeft.getTitle());
        values.put(TimeLeft.KEY_BEGIN_TIME,timeLeft.getBeginDate());
        values.put(TimeLeft.KEY_DESCRIPTION,timeLeft.getContent());
        values.put(TimeLeft.KEY_IMPORTANCE,timeLeft.getImportance());
        values.put(TimeLeft.KEY_STATE,timeLeft.getState());
        values.put(TimeLeft.KEY_END_TIME,timeLeft.getEndDate());


        // It's a good practice to use parameter ?, instead of concatenate string

        db.update(TimeLeft.TABLE, values, TimeLeft.KEY_ID + " = ?", new String[] { String.valueOf(timeLeft.ID) });
        Log.e("timeLeft sta "+timeLeft.getState(),"has changed in db");
        db.close(); // Closing database connection
    }
项目:PeSanKita-android    文件:GroupDatabase.java   
public void update(byte[] groupId, String title, SignalServiceAttachmentPointer avatar) {
  ContentValues contentValues = new ContentValues();
  if (title != null) contentValues.put(TITLE, title);

  if (avatar != null) {
    contentValues.put(AVATAR_ID, avatar.getId());
    contentValues.put(AVATAR_CONTENT_TYPE, avatar.getContentType());
    contentValues.put(AVATAR_KEY, avatar.getKey());
  }

  databaseHelper.getWritableDatabase().update(TABLE_NAME, contentValues,
                                              GROUP_ID + " = ?",
                                              new String[] {GroupUtil.getEncodedId(groupId)});

  RecipientFactory.clearCache(context);
  notifyDatabaseListeners();
  notifyConversationListListeners();
}
项目:Melophile    文件:DatabaseUtils.java   
public static ContentValues toValues(User user){
    if(user==null) return null;
    ContentValues values=new ContentValues();
    values.put(Users.USER_ID,user.getId());
    values.put(Users.USER_ART_URL,user.getAvatarUrl());
    values.put(Users.USER_NICKNAME,user.getNickName());
    values.put(Users.USER_FULLNAME,user.getFullName());
    values.put(Users.USER_DESCRIPTION,user.getDescription());
    values.put(Users.USER_FOLLOWINGS_COUNT,user.getFollowingCount());
    values.put(Users.USER_FOLLOWER_COUNT,user.getFollowersCount());
    values.put(Users.USER_TRACKS_COUNT,user.getTracksCount());
    values.put(Users.USER_LIKED_TRACKS_COUNT,user.getLikedTracksCount());
    values.put(Users.USER_IS_FOLLOWED,user.isFollowed()?1:0);
    values.put(Users.USER_PLAYLISTS_COUNT,user.getPlaylistsCount());
    return values;
}
项目:robird-reborn    文件:Tweet.java   
public ContentValues toContentValues() {
    ContentValues values = new ContentValues();

    values.put(TweetContract.TWEET_ID, tweetId());
    values.put(TweetContract.TEXT, text());
    values.put(TweetContract.SOURCE, source());
    values.put(TweetContract.AVATAR, avatar());
    values.put(TweetContract.TWEET_ID, tweetId());
    values.put(TweetContract.CREATED_AT, createdAt());
    values.put(TweetContract.FAVORITED, favorited());
    values.put(TweetContract.FULLNAME, fullname());
    values.put(TweetContract.MEDIA, media());
    values.put(TweetContract.VIDEO, video());
    values.put(TweetContract.MENTIONS, mentions());
    values.put(TweetContract.USERNAME, username());
    values.put(TweetContract.RETWEETED_BY, retweetedBy());
    values.put(TweetContract.RETWEETED_BY_ME, retweetedByMe());
    values.put(TweetContract.IN_REPLY_TO_STATUS, inReplyToStatus());
    values.put(TweetContract.QUOTED_SCREEN_NAME, quotedScreenName());
    values.put(TweetContract.QUOTED_TEXT, quotedText());
    values.put(TweetContract.QUOTED_NAME, quotedName());
    values.put(TweetContract.QUOTED_MEDIA, quotedMedia());
    values.put(TweetContract.QUOTED_ID, quotedId());

    return values;
}
项目:android-dev-challenge    文件:TestUtilities.java   
/**
 * Used as a convenience method to return a singleton instance of ContentValues to populate
 * our database or insert using our ContentProvider.
 *
 * @return ContentValues that can be inserted into our ContentProvider or weather.db
 */
static ContentValues createTestWeatherContentValues() {

    ContentValues testWeatherValues = new ContentValues();

    testWeatherValues.put(COLUMN_DATE, DATE_NORMALIZED);
    testWeatherValues.put(COLUMN_DEGREES, 1.1);
    testWeatherValues.put(COLUMN_HUMIDITY, 1.2);
    testWeatherValues.put(COLUMN_PRESSURE, 1.3);
    testWeatherValues.put(COLUMN_MAX_TEMP, 75);
    testWeatherValues.put(COLUMN_MIN_TEMP, 65);
    testWeatherValues.put(COLUMN_WIND_SPEED, 5.5);
    testWeatherValues.put(COLUMN_WEATHER_ID, 321);

    return testWeatherValues;
}
项目:IdeaTrackerPlus    文件:DatabaseHelper.java   
/**
 * Reset the order indexes of the ideas to match the order displayed
 * Usefull after a manual reorder (long click)
 *
 * @param tabNumber
 */
public void resetEntriesOrderAt(int tabNumber) {

    //Get the list with right order
    List<Pair<Integer, String>> itemList = adapters[tabNumber].getItemList();

    SQLiteDatabase db = this.getWritableDatabase();
    int indexOrder = 0;

    for (Pair<Integer, String> item : itemList) {
        ContentValues values = new ContentValues();
        values.put(DataEntry.COLUMN_NAME_ENTRY_ID, indexOrder);
        db.update(DataEntry.TABLE_NAME, values, "_id=" + item.first, null);
        indexOrder++;
    }

}
项目:USay    文件:FavoriteDB.java   
public void saveFavorite(Favorite favorite) {
    if (favorite != null) {
        ContentValues values = new ContentValues();
        values.put("new_id", favorite.getNewId());
        values.put("author", favorite.getAuthor());
        values.put("url", favorite.getUrl());
        values.put("image", favorite.getImage());
        values.put("title", favorite.getTitle());
        mDatabase.insert("favorite", null, values);
    }
}
项目:LifeSaver    文件:DatabaseFriend.java   
public void addContact(Friends contact) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();

    values.put(KEY_NAME, contact.getName()); // Contact Name
    values.put(KEY_DNAME, contact.getNameD());
    values.put(KEY_DDNAME, contact.getNameDD());
    // Inserting Row
    db.insert(TABLE_CONTACTS, null, values);

    db.close(); // Closing database connection
}
项目:YuiHatano    文件:ShadowDatabaseUtils.java   
/**
 * Reads a Double out of a field in a Cursor and writes it to a Map.
 *
 * @param cursor The cursor to read from
 * @param field  The REAL field to read
 * @param values The {@link ContentValues} to put the value into
 * @param key    The key to store the value with in the map
 */
public static void cursorDoubleToContentValues(Cursor cursor, String field,
                                               ContentValues values, String key) {
    int colIndex = cursor.getColumnIndex(field);
    if (!cursor.isNull(colIndex)) {
        values.put(key, cursor.getDouble(colIndex));
    } else {
        values.put(key, (Double) null);
    }
}
项目:AsyncQuery    文件:DataProvider.java   
private int insertInBulk(SQLiteDatabase database, String tableName, ContentValues[] values) {
    database.beginTransaction();

    for (ContentValues value : values) {
        database.insertOrThrow(tableName, null, value);
    }

    database.setTransactionSuccessful();
    database.endTransaction();
    return values.length;
}
项目:OpenHomeAnalysis    文件:OhaEnergyUseContract.java   
/**
 * Analisar e validar um conta de utilização de energia
 */
public static ContentValues parse(Date from, Date to, double kwhCost) {
    ContentValues contentValues = new ContentValues();
    contentValues.put(COLUMN_FROM, OhaHelper.getDateBegin(from).getTime());
    contentValues.put(COLUMN_TO, OhaHelper.getDateEnd(to, false).getTime());
    contentValues.put(COLUMN_KWH_COST, kwhCost);
    return contentValues;
}
项目:Cable-Android    文件:MmsDatabase.java   
public void markDownloadState(long messageId, long state) {
  SQLiteDatabase database     = databaseHelper.getWritableDatabase();
  ContentValues contentValues = new ContentValues();
  contentValues.put(STATUS, state);

  database.update(TABLE_NAME, contentValues, ID_WHERE, new String[] {messageId + ""});
  notifyConversationListeners(getThreadIdForMessage(messageId));
}
项目:android-sql-crud    文件:MyDataBaseHelper.java   
public int updateNamaSantri(String id, String nama) {
    SQLiteDatabase db = this.getWritableDatabase();

    //prepare content values
    ContentValues values = new ContentValues();

    //put the value
    values.put(NAMA_SANTRI, nama);

    // updating row
    return db.update(TABLE_SANTRI, values, ID_SANTRI + " = ?",
            new String[] { id });
}
项目:MyBP    文件:PlanTable.java   
public long insert() {
    SQLiteDatabase database = DatabaseHelper.getInstance(DatabaseHelper.getDhContext()).getWritableDatabase();
    ContentValues values = new ContentValues();

    values.put(TITLE, getTitle());
    values.put(TYPE, getType());
    values.put(FROM, getFrom());
    values.put(TO, getTo());
    values.put(CREATED, getCreated());
    values.put(UPDATED, getUpdated());

    return database.insert(name, null, values);
}
项目:aos-MediaLib    文件:DBPersistence.java   
public void storeData(String key, Object data) {

    byte[] ba = (byte[])data;
    if (ba != null) {

        ContentValues values = new ContentValues();
        values.put(DBImageTable.NAME, key);
        values.put(DBImageTable.DATA, ba);
        values.put(DBImageTable.SIZE, ba.length);
        values.put(DBImageTable.NUSE, 1);
        values.put(DBImageTable.TIMESTAMP, System.currentTimeMillis());
        mContext.getContentResolver().insert(DBImageTable.CONTENT_URI, values);
    }
}
项目:AndroidProgramming3e    文件:CrimeLab.java   
private static ContentValues getContentValues(Crime crime) {
    ContentValues values = new ContentValues();
    values.put(UUID, crime.getId().toString());
    values.put(TITLE, crime.getTitle());
    values.put(DATE, crime.getDate().getTime());
    values.put(SOLVED, crime.isSolved() ? 1 : 0);
    values.put(CrimeTable.Cols.SUSPECT, crime.getSuspect());

    return values;
}
项目:Bigbang    文件:SelectionDbHelper.java   
public void insertAll(List<AppListAdapter.ApplicationInfoWrap> apps){
    SQLiteDatabase dataBase=getWritableDatabase();
    dataBase.delete(TABLE_NAME,null,null);
    dataBase.beginTransaction();       //手动设置开始事务
    //数据插入操作循环
    for (AppListAdapter.ApplicationInfoWrap wrap:apps){
        ContentValues values=new ContentValues();
        values.put(COLUMN_PACKAGE,wrap.applicationInfo.packageName);
        values.put(COLUMN_TYPE,wrap.selection);
        dataBase.insert(TABLE_NAME,null,values);
    }
    dataBase.setTransactionSuccessful();       //设置事务处理成功,不设置会自动回滚不提交
    dataBase.endTransaction();       //处理完成
    dataBase.close();
}
项目:oma-riista-android    文件:StorageDatabase.java   
public void updateAnnouncement(final Announcement item, final UpdateListener listener) {
    StorageDatabaseHelper helper = StorageDatabaseHelper.getInstance();
    final String userName = BaseDatabase.getUsername();

    helper.write(new AsyncDatabase.AsyncWrite() {
        @Override
        protected void onAsyncWrite(SQLiteDatabase db) {
            ContentValues values = announcementToValues(item, userName);

            //First try to update existing entry with a specific remoteId
            int changes = db.update("announcement", values, "remoteId = ? AND userName = ?",
                    new String[] {"" + item.remoteId, userName});
            if (changes == 0) {
                //Row does not exist, so insert it now.
                db.insert("announcement", null, values);
            }
        }

        @Override
        protected void onFinish() {
            if (listener != null)
                listener.onUpdate();
        }

        @Override
        protected void onError() {
            if (listener != null)
                listener.onError();
        }
    });
}
项目:RetrofitAppArchitecture    文件:Utils.java   
public static ContentValues map2ContentValues(Map<String, Object> map) {
    ContentValues values = new ContentValues();
    if (map != null && map.size() > 0) {
        Set<Map.Entry<String, Object>> set = map.entrySet();
        Iterator<Map.Entry<String, Object>> itr = set.iterator();
        while (itr.hasNext()) {
            Map.Entry<String, Object> entry = itr.next();
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value != null) {
                if (value instanceof String) {
                    values.put(key, (String) value);
                } else if (value instanceof Integer) {
                    values.put(key, (Integer) value);
                } else if (value instanceof Float) {
                    values.put(key, (Float) value);
                } else {
                    LogUtils.d("未知的参数类型,key:" + key + ",value:" + value);

                }
            } else {
                LogUtils.d("未知的参数类型,key:" + key + ",value:" + value);
            }
        }
    }
    return values;
}
项目:VirtualAPK    文件:BookProvider.java   
@Override
public int update(Uri uri, ContentValues values, String selection,
        String[] selectionArgs) {
    Log.d(TAG, "update");
    String table = getTableName(uri);
    if (table == null) {
        throw new IllegalArgumentException("Unsupported URI: " + uri);
    }
    int row = mDb.update(table, values, selection, selectionArgs);
    if (row > 0) {
        getContext().getContentResolver().notifyChange(uri, null);
    }
    return row;
}
项目:NeteaseCloudMusic    文件:PlaylistModel.java   
public int newPlaylist(String name) {
    SQLiteDatabase db = mDBHelper.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put("name", name);
    db.insert("playlist", null, values);

    Cursor cursor = db.rawQuery("select list_id from playlist where rowid==last_insert_rowid();", null);
    int listID=-2;
    if (cursor.moveToFirst()) {
        listID = cursor.getInt(0);
    }
    cursor.close();
    db.close();
    return listID;
}
项目:android-dev-challenge    文件:TestUtilities.java   
/**
 * Used as a convenience method to return a singleton instance of an array of ContentValues to
 * populate our database or insert using our ContentProvider's bulk insert method.
 * <p>
 * It is handy to have utility methods that produce test values because it makes it easy to
 * compare results from ContentProviders and databases to the values you expect to receive.
 * See {@link #validateCurrentRecord(String, Cursor, ContentValues)} and
 * {@link #validateThenCloseCursor(String, Cursor, ContentValues)} for more information on how
 * this verification is performed.
 *
 * @return Array of ContentValues that can be inserted into our ContentProvider or weather.db
 */
static ContentValues[] createBulkInsertTestWeatherValues() {

    ContentValues[] bulkTestWeatherValues = new ContentValues[BULK_INSERT_RECORDS_TO_INSERT];

    long testDate = TestUtilities.DATE_NORMALIZED;
    long normalizedTestDate = SunshineDateUtils.normalizeDate(testDate);

    for (int i = 0; i < BULK_INSERT_RECORDS_TO_INSERT; i++) {

        normalizedTestDate += SunshineDateUtils.DAY_IN_MILLIS;

        ContentValues weatherValues = new ContentValues();

        weatherValues.put(COLUMN_DATE, normalizedTestDate);
        weatherValues.put(COLUMN_DEGREES, 1.1);
        weatherValues.put(COLUMN_HUMIDITY, 1.2 + 0.01 * (float) i);
        weatherValues.put(COLUMN_PRESSURE, 1.3 - 0.01 * (float) i);
        weatherValues.put(COLUMN_MAX_TEMP, 75 + i);
        weatherValues.put(COLUMN_MIN_TEMP, 65 - i);
        weatherValues.put(COLUMN_WIND_SPEED, 5.5 + 0.2 * (float) i);
        weatherValues.put(COLUMN_WEATHER_ID, 321);

        bulkTestWeatherValues[i] = weatherValues;
    }

    return bulkTestWeatherValues;
}
项目:Phoenix-for-VK    文件:UserCareerColumns.java   
public static ContentValues getCV(@NonNull VKApiCareer career, int userId){
    ContentValues cv = new ContentValues();
    cv.put(USER_ID, userId);
    cv.put(GROUP_ID, career.group_id);
    cv.put(COMPANY, career.company);
    cv.put(COUNTRY_ID, career.country_id);
    cv.put(CITY_ID, career.city_id);
    cv.put(CITY_NAME, career.city_name);
    cv.put(YEAR_FROM, career.from);
    cv.put(YEAR_UNTIL, career.until);
    cv.put(POSITION, career.position);
    return cv;
}
项目:ChatKeyboard-master    文件:EmoticonDBHelper.java   
public ContentValues createEmoticonSetContentValues(EmoticonBean bean, String beanSetName) {
    if (bean == null) {
        return null;
    }
    ContentValues values = new ContentValues();
    values.put(TableColumns.EmoticonColumns.EVENT_TYPE, bean.getEventType());
    values.put(TableColumns.EmoticonColumns.TAG, bean.getTag());
    values.put(TableColumns.EmoticonColumns.NAME, bean.getName());
    values.put(TableColumns.EmoticonColumns.ICON_URI, bean.getIconUri());
    values.put(TableColumns.EmoticonColumns.MSG_URI, bean.getMsgUri());
    values.put(TableColumns.EmoticonColumns.EMOTICON_SET_NAME, beanSetName);
    return values;
}
项目:amap    文件:MIPDBProvider.java   
@Override
public Uri insert(Uri uri, ContentValues values)
{
    if ((null == values) || (0 == values.size()) || (null == uri))
    {
        return null;
    }

    String tableName = getTableName(uri);
    if (null == tableName)
    {
        throw new IllegalArgumentException(Constant_DB.CONTENTPROVIDER_UNRECOGNIZED_URI + uri);
    }

    SQLiteDatabase db = MIPProvider.getWritableDatabase();
    long row = db.insert(tableName, null, values);
    // long row = db.replace(tableName, "NULL", values);
    if (row > 0)
    {
        getContext().getContentResolver().notifyChange(uri, null);
        return ContentUris.withAppendedId(uri, row);
    }
    else
    {
        try
        {
            throw new SqlException();

        }
        catch (SqlException e)
        {
            e.printStackTrace();
        }
        return null;
    }

}
项目:IslamicLibraryAndroid    文件:BooksInformationDbHelper.java   
/**
 * @param enqueueId      The download reference got from DownloadManager
 * @param downloadStatus the status to register see {@link DownloadsConstants}
 * @return true if this download reference already exist in the database i.e this download was requsted by this app
 */
public boolean setDownloadStatusByEnquId(long enqueueId, int downloadStatus) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(BooksInformationDBContract.StoredBooks.COLUMN_NAME_STATUS, downloadStatus);
    //TODO add
    int i = db.update(BooksInformationDBContract.StoredBooks.TABLE_NAME, contentValues,
            BooksInformationDBContract.StoredBooks.COLUMN_NAME_ENQID + "=?",
            new String[]{Long.toString(enqueueId)});
    return i == 1;
}
项目:sekai    文件:UserRepo.java   
public void update(User user)
{
    SQLiteDatabase db = dbHandler.getWritableDatabase();
    ContentValues values = new ContentValues();

    values.put(User.KEY_ID, user.id);
    values.put(User.KEY_LAST_NAME, user.last_name);
    values.put(User.KEY_FIRST_NAME, user.first_name);
    values.put(User.KEY_EMAIL, user.email);
    values.put(User.KEY_COUNTRY, user.home_country);

    // It's a good practice to use parameter ?, instead of concatenate string
    db.update(User.TABLE, values, User.KEY_ID + "= ?", new String[] { String.valueOf(user.id) });
    db.close(); // Closing database connection
}
项目:uidcore-android    文件:Register.java   
/**
 * Creates a {@code ProviderChannel} by persisting its content in the data store
 * @param providerChannel the {@code ProviderChannel} to persist
 * @throws RegisterException in case a problem occurs or the specified {@code ProviderChannel} is already present
 * */
public void insertChannel(ProviderChannel providerChannel) throws RegisterException{

    if(providerChannel == null)
        throw new RegisterException("providerChannel is null!");

    try {
        try (SQLiteHelperPool.SQLiteDatabaseWrapper sqLiteDatabaseWrapper =
                     androidDataSource.getSQLiteDatabaseWrapper()) {

            SQLiteDatabase db = sqLiteDatabaseWrapper.getSQLiteDatabase();

            ContentValues values = new ContentValues();
            values.put(SQLiteHelper.PROVIDER_CLM_PROVIDER_ADDRESS, providerChannel.getProviderAddress());
            values.put(SQLiteHelper.PROVIDER_CLM_USER_ADDRESS, providerChannel.getUserAddress());
            values.put(SQLiteHelper.PROVIDER_CLM_BITMASK, providerChannel.getBitmask());
            values.put(SQLiteHelper.PROVIDER_CLM_REVOKE_ADDRESS, providerChannel.getRevokeAddress());
            values.put(SQLiteHelper.PROVIDER_CLM_REVOKE_TX_ID, providerChannel.getRevokeTxId());
            values.put(SQLiteHelper.PROVIDER_CLM_CREATION_TIME, providerChannel.getCreationTime());
            long db_index = db.insert(SQLiteHelper.TABLE_PROVIDER, null, values);
            if (db_index < 0)
                throw new RegisterException("Exception while insertChannel()");
        }
    } catch (Throwable t) {

        throw new RegisterException("Exception while insertChannel()", t);

    }
}