Java Code Examples for android.content.ContentValues

The following are top voted examples for showing how to use android.content.ContentValues. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Udhari   File: TxProvider.java   Source Code and License 7 votes vote down vote up
@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;
}
 
Example 2
Project: springreplugin   File: PluginProviderClient.java   Source Code and License 6 votes vote down vote up
/**
 * 调用插件里的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;
}
 
Example 3
Project: ubiquitous   File: TestUtilities.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 4
Project: android-sql-crud   File: MyDataBaseHelper.java   Source Code and License 6 votes vote down vote up
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 });
}
 
Example 5
Project: OpenHomeAnalysis   File: OhaEnergyUseProvider.java   Source Code and License 6 votes vote down vote up
@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);
    }
}
 
Example 6
Project: Cable-Android   File: AttachmentDatabase.java   Source Code and License 6 votes vote down vote up
@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();
  }
}
 
Example 7
Project: LucaHome-AndroidApplication   File: DatabaseMenuList.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 8
Project: GiphyImageResultsPreview   File: Helper.java   Source Code and License 6 votes vote down vote up
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;
        }
    }
}
 
Example 9
Project: unity-obb-downloader   File: DownloadsDB.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
}
 
Example 10
Project: Todule-android   File: ToduleProvider.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 11
Project: pets   File: PetProvider.java   Source Code and License 6 votes vote down vote up
/**
 * ********** 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);
    }
}
 
Example 12
Project: ChatKeyboard-master   File: EmoticonDBHelper.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 13
Project: GitHub   File: HostBean.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 14
Project: Sanxing   File: TimeLeftRepo.java   Source Code and License 6 votes vote down vote up
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
    }
 
Example 15
Project: PeSanKita-android   File: GroupDatabase.java   Source Code and License 6 votes vote down vote up
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();
}
 
Example 16
Project: Melophile   File: DatabaseUtils.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 17
Project: robird-reborn   File: Tweet.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 18
Project: android-dev-challenge   File: TestUtilities.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 19
Project: IdeaTrackerPlus   File: DatabaseHelper.java   Source Code and License 6 votes vote down vote up
/**
 * 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++;
    }

}
 
Example 20
Project: USay   File: FavoriteDB.java   Source Code and License 5 votes vote down vote up
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);
    }
}
 
Example 21
Project: LifeSaver   File: DatabaseFriend.java   Source Code and License 5 votes vote down vote up
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
}
 
Example 22
Project: YuiHatano   File: ShadowDatabaseUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 23
Project: AsyncQuery   File: DataProvider.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 24
Project: OpenHomeAnalysis   File: OhaEnergyUseContract.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 25
Project: Cable-Android   File: MmsDatabase.java   Source Code and License 5 votes vote down vote up
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));
}
 
Example 26
Project: MyBP   File: PlanTable.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 27
Project: aos-MediaLib   File: DBPersistence.java   Source Code and License 5 votes vote down vote up
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);
    }
}
 
Example 28
Project: AndroidProgramming3e   File: CrimeLab.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 29
Project: Bigbang   File: SelectionDbHelper.java   Source Code and License 5 votes vote down vote up
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();
}
 
Example 30
Project: oma-riista-android   File: StorageDatabase.java   Source Code and License 5 votes vote down vote up
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();
        }
    });
}
 
Example 31
Project: RetrofitAppArchitecture   File: Utils.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 32
Project: VirtualAPK   File: BookProvider.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 33
Project: NeteaseCloudMusic   File: PlaylistModel.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 34
Project: android-dev-challenge   File: TestUtilities.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 35
Project: Phoenix-for-VK   File: UserCareerColumns.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 36
Project: ChatKeyboard-master   File: EmoticonDBHelper.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 37
Project: amap   File: MIPDBProvider.java   Source Code and License 5 votes vote down vote up
@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;
    }
    
}
 
Example 38
Project: IslamicLibraryAndroid   File: BooksInformationDbHelper.java   Source Code and License 5 votes vote down vote up
/**
 * @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;
}
 
Example 39
Project: sekai   File: UserRepo.java   Source Code and License 5 votes vote down vote up
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
}
 
Example 40
Project: uidcore-android   File: Register.java   Source Code and License 5 votes vote down vote up
/**
 * 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);

    }
}
 
Example 41
Project: LucaHome-AndroidApplication   File: DatabaseBixbyActionList.java   Source Code and License 5 votes vote down vote up
public boolean Update(@NonNull BixbyAction updateEntry) throws SQLException {
    ContentValues contentValues = new ContentValues();

    contentValues.put(KEY_ROW_ID, updateEntry.GetId());
    contentValues.put(KEY_ACTION_ID, updateEntry.GetActionId());
    contentValues.put(KEY_ACTION_TYPE, String.valueOf(updateEntry.GetActionType().ordinal()));
    contentValues.put(KEY_APPLICATION_ACTION, updateEntry.GetApplicationAction().GetDatabaseString());
    contentValues.put(KEY_NETWORK_ACTION, updateEntry.GetNetworkAction().GetDatabaseString());
    contentValues.put(KEY_WIRELESSSOCKET_ACTION, updateEntry.GetWirelessSocketAction().GetDatabaseString());

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

    return true;
}
 
Example 42
Project: Cash   File: tblVendaItens.java   Source Code and License 5 votes vote down vote up
private ContentValues getValues() {

        ContentValues values = new ContentValues();

        values.put("id_venda_item", getIdItem());
        values.put("id_venda", getIdVenda());
        values.put("id_produto", getIdProduto());
        values.put("qt_itens", getQtItens());
        values.put("vlr_unitario", getVlrUnitario());
        values.put("observacoes", getObservacoes());
        values.put("dt_venda", getDtVenda());
        values.put("dt_venda_inv", getDtVendaInv());

        return values;
    }
 
Example 43
Project: AndroidSnooper   File: SnooperRepo.java   Source Code and License 5 votes vote down vote up
private void saveHeader(SQLiteDatabase database, HttpHeader httpHeader, long httpCallRecordId, String headerType) {
  ContentValues values = new ContentValues();
  values.put(COLUMN_HEADER_NAME, httpHeader.getName());
  values.put(COLUMN_HEADER_TYPE, headerType);
  values.put(COLUMN_HTTP_CALL_RECORD_ID, httpCallRecordId);
  long headerId = database.insert(HEADER_TABLE_NAME, null, values);
  for (HttpHeaderValue httpHeaderValue : httpHeader.getValues()) {
    saveHeaderValue(database, httpHeaderValue, headerId);
  }
}
 
Example 44
Project: permissions4m   File: PermissionsChecker.java   Source Code and License 5 votes vote down vote up
/**
 * write or delete call log, {@link android.Manifest.permission#WRITE_CALL_LOG}
 *
 * @param activity
 * @return true if success
 */
private static boolean checkWriteCallLog(Activity activity) throws Exception {
    ContentResolver contentResolver = activity.getContentResolver();
    ContentValues content = new ContentValues();
    content.put(CallLog.Calls.TYPE, CallLog.Calls.INCOMING_TYPE);
    content.put(CallLog.Calls.NUMBER, TAG_NUMBER);
    content.put(CallLog.Calls.DATE, 20140808);
    content.put(CallLog.Calls.NEW, "0");
    contentResolver.insert(Uri.parse("content://call_log/calls"), content);

    contentResolver.delete(Uri.parse("content://call_log/calls"), "number = ?", new
            String[]{TAG_NUMBER});

    return true;
}
 
Example 45
Project: 3D5B   File: DatabaseHelper.java   Source Code and License 5 votes vote down vote up
public boolean insert_users(String first_name, String last_name, String e_mail, String password, String user, String department){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_1, first_name);
    contentValues.put(COL_2, last_name);
    contentValues.put(COL_3, e_mail);
    contentValues.put(COL_4, password);
    contentValues.put(COL_5, user);
    contentValues.put(COL_6, department);
    long result=db.insert(table_user, null, contentValues);
    if(result==-1)
        return false;
    else
        return true;
}
 
Example 46
Project: orgzly-android   File: NotesClient.java   Source Code and License 5 votes vote down vote up
public static int delete(Context context, long bookId, Set<Long> noteIds) {
    ContentValues values = new ContentValues();

    values.put(ProviderContract.Delete.Param.BOOK_ID, bookId);
    values.put(ProviderContract.Delete.Param.IDS, TextUtils.join(",", noteIds));

    return context.getContentResolver().update(ProviderContract.Delete.ContentUri.delete(), values, null, null);
}
 
Example 47
Project: GitHub   File: AbstractBean.java   Source Code and License 5 votes vote down vote up
public String toXML() {
	XmlBuilder xml = new XmlBuilder();

	xml.append(String.format("<%s>", getBeanName()));

	ContentValues values = getValues();
	for (Entry<String, Object> entry : values.valueSet()) {
		Object value = entry.getValue();
		if (value != null)
			xml.append(entry.getKey(), value);
	}
	xml.append(String.format("</%s>", getBeanName()));

	return xml.toString();
}
 
Example 48
Project: KBUnitTest   File: ShadowDatabaseUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Reads a Long out of a field in a Cursor and writes it to a Map.
 *
 * @param cursor The cursor to read from
 * @param field  The INTEGER 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 cursorLongToContentValues(Cursor cursor, String field, ContentValues values,
                                             String key) {
    int colIndex = cursor.getColumnIndex(field);
    if (!cursor.isNull(colIndex)) {
        Long value = Long.valueOf(cursor.getLong(colIndex));
        values.put(key, value);
    } else {
        values.put(key, (Long) null);
    }
}
 
Example 49
Project: SimpleUILauncher   File: RestoreDbTask.java   Source Code and License 5 votes vote down vote up
/**
 * Updates profile id of all entries and changes the default value for the column.
 */
protected void migrateProfileId(SQLiteDatabase db, long newProfileId) {
    // Update existing entries.
    ContentValues values = new ContentValues();
    values.put(Favorites.PROFILE_ID, newProfileId);
    db.update(Favorites.TABLE_NAME, values, null, null);

    // Change default value of the column.
    db.execSQL("ALTER TABLE favorites RENAME TO favorites_old;");
    Favorites.addTableToDb(db, newProfileId, false);
    db.execSQL("INSERT INTO favorites SELECT * FROM favorites_old;");
    db.execSQL("DROP TABLE favorites_old;");
}
 
Example 50
Project: XERUNG   File: GroupDb.java   Source Code and License 5 votes vote down vote up
public int addGroup(GroupBean gb) {
    //Log.e("ADD GROUP", "ADD GROUP");
    int status = 0;
    try {
        SQLiteDatabase sq = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(T_GROUPID, Integer.parseInt(gb.getmGroupId().trim()));
        cv.put(T_GROUPNAME, gb.getmGroupName().trim());

        cv.put(T_MADEBYNAME, gb.getmGroupMadeByName().trim());
        cv.put(T_MADEBYPHONENO, gb.getmGroupMadeByNum().trim());
        cv.put(T_TAGNAME, gb.getmGroupTag().trim());
        cv.put(T_DESCRITION, gb.getmGroupDesc().trim());
        cv.put(T_GROUPPHOTO, gb.getmPhoto().trim());
        cv.put(T_MEMBERCOUNT, String.valueOf(gb.getmGroupSize()));
        cv.put(T_ACCESS_TYPE, gb.getmGroupAccessType().trim());
        cv.put(T_ADMINFLAG, gb.getmGroupAdmin());
        cv.put(T_CREATEUPDATETS, gb.getmGroupCreatedDate());
        sq.insert(TABLE_NAME, null, cv);
        status = 1;
        sq.close();
    } catch (Exception e) {
        // TODO: handle exception
        status = 0;
        //Log.e("GroupDBErro", "AddGroup "+e.getMessage());
        e.printStackTrace();
    }
    return status;
}
 
Example 51
Project: PeSanKita-android   File: MmsDatabase.java   Source Code and License 5 votes vote down vote up
public List<MarkedMessageInfo> setMessagesRead(long threadId) {
  SQLiteDatabase          database  = databaseHelper.getWritableDatabase();
  String                  where     = THREAD_ID + " = ? AND " + READ + " = 0";
  String[]                selection = new String[]{String.valueOf(threadId)};
  List<MarkedMessageInfo> result    = new LinkedList<>();
  Cursor                  cursor    = null;

  database.beginTransaction();

  try {
    cursor = database.query(TABLE_NAME, new String[] {ID, ADDRESS, DATE_SENT, MESSAGE_BOX, EXPIRES_IN, EXPIRE_STARTED}, where, selection, null, null, null);

    while(cursor != null && cursor.moveToNext()) {
      if (Types.isSecureType(cursor.getLong(3))) {
        SyncMessageId  syncMessageId  = new SyncMessageId(cursor.getString(1), cursor.getLong(2));
        ExpirationInfo expirationInfo = new ExpirationInfo(cursor.getLong(0), cursor.getLong(4), cursor.getLong(5), true);

        result.add(new MarkedMessageInfo(syncMessageId, expirationInfo));
      }
    }

    ContentValues contentValues = new ContentValues();
    contentValues.put(READ, 1);

    database.update(TABLE_NAME, contentValues, where, selection);
    database.setTransactionSuccessful();
  } finally {
    if (cursor != null) cursor.close();
    database.endTransaction();
  }

  return result;
}
 
Example 52
Project: CSipSimple   File: UAStateReceiver.java   Source Code and License 5 votes vote down vote up
@Override
public void on_pager_status(int callId, pj_str_t to, pj_str_t body, pjsip_status_code status,
        pj_str_t reason) {
    lockCpu();
    // TODO : treat error / acknowledge of messages
    int messageType = (status.equals(pjsip_status_code.PJSIP_SC_OK)
            || status.equals(pjsip_status_code.PJSIP_SC_ACCEPTED)) ? SipMessage.MESSAGE_TYPE_SENT
            : SipMessage.MESSAGE_TYPE_FAILED;
    String toStr = SipUri.getCanonicalSipContact(PjSipService.pjStrToString(to));
    String reasonStr = PjSipService.pjStrToString(reason);
    String bodyStr = PjSipService.pjStrToString(body);
    int statusInt = status.swigValue();
    Log.d(THIS_FILE, "SipMessage in on pager status " + status.toString() + " / " + reasonStr);

    // Update the db
    ContentResolver cr = pjService.service.getContentResolver();
    ContentValues args = new ContentValues();
    args.put(SipMessage.FIELD_TYPE, messageType);
    args.put(SipMessage.FIELD_STATUS, statusInt);
    if (statusInt != StatusCode.OK
            && statusInt != StatusCode.ACCEPTED) {
        args.put(SipMessage.FIELD_BODY, bodyStr + " // " + reasonStr);
    }
    cr.update(SipMessage.MESSAGE_URI, args,
            SipMessage.FIELD_TO + "=? AND " +
                    SipMessage.FIELD_BODY + "=? AND " +
                    SipMessage.FIELD_TYPE + "=" + SipMessage.MESSAGE_TYPE_QUEUED,
            new String[] {
                    toStr, bodyStr
            });

    // Broadcast the information
    Intent intent = new Intent(SipManager.ACTION_SIP_MESSAGE_RECEIVED);
    intent.putExtra(SipMessage.FIELD_FROM, toStr);
    pjService.service.sendBroadcast(intent, SipManager.PERMISSION_USE_SIP);
    unlockCpu();
}
 
Example 53
Project: kennethrey13-android-studio-crud-with-customlistview   File: DatabaseHelper.java   Source Code and License 5 votes vote down vote up
public void addNewStudent(StudentClass studObj){
    ContentValues values = new ContentValues();
    values.put(STUDENT_FIRST_NAME,studObj.getFirstName());
    values.put(STUDENT_LAST_NAME,studObj.getLastName());
    values.put(STUDENT_PRELIM,studObj.getPG());
    values.put(STUDENT_MIDTERM,studObj.getMG());
    values.put(STUDENT_FINALS,studObj.getFG());
    values.put(STUDENT_PROGRAM,studObj.getProgram());
    dbDatabase.insert(TABLE_STUDENT, null, values);
}
 
Example 54
Project: PeSanKita-android   File: AttachmentDatabase.java   Source Code and License 5 votes vote down vote up
public @NonNull Attachment updateAttachmentData(@NonNull MasterSecret masterSecret,
                                                @NonNull Attachment attachment,
                                                @NonNull MediaStream mediaStream)
    throws MmsException
{
  SQLiteDatabase     database           = databaseHelper.getWritableDatabase();
  DatabaseAttachment databaseAttachment = (DatabaseAttachment) attachment;
  File               dataFile           = getAttachmentDataFile(databaseAttachment.getAttachmentId(), DATA);

  if (dataFile == null) {
    throw new MmsException("No attachment data found!");
  }

  long dataSize = setAttachmentData(masterSecret, dataFile, mediaStream.getStream());

  ContentValues contentValues = new ContentValues();
  contentValues.put(SIZE, dataSize);
  contentValues.put(CONTENT_TYPE, mediaStream.getMimeType());

  database.update(TABLE_NAME, contentValues, PART_ID_WHERE, databaseAttachment.getAttachmentId().toStrings());

  return new DatabaseAttachment(databaseAttachment.getAttachmentId(),
                                databaseAttachment.getMmsId(),
                                databaseAttachment.hasData(),
                                databaseAttachment.hasThumbnail(),
                                mediaStream.getMimeType(),
                                databaseAttachment.getFilename(),
                                databaseAttachment.getTransferState(),
                                dataSize,
                                databaseAttachment.getLocation(),
                                databaseAttachment.getKey(),
                                databaseAttachment.getRelay());
}
 
Example 55
Project: android-dev-challenge   File: WeatherProvider.java   Source Code and License 5 votes vote down vote up
/**
 * Handles requests to insert a set of new rows. In Sunshine, we are only going to be
 * inserting multiple rows of data at a time from a weather forecast. There is no use case
 * for inserting a single row of data into our ContentProvider, and so we are only going to
 * implement bulkInsert. In a normal ContentProvider's implementation, you will probably want
 * to provide proper functionality for the insert method as well.
 *
 * @param uri    The content:// URI of the insertion request.
 * @param values An array of sets of column_name/value pairs to add to the database.
 *               This must not be {@code null}.
 *
 * @return The number of values that were inserted.
 */
@Override
public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
    final SQLiteDatabase db = mOpenHelper.getWritableDatabase();

    switch (sUriMatcher.match(uri)) {

        case CODE_WEATHER:
            db.beginTransaction();
            int rowsInserted = 0;
            try {
                for (ContentValues value : values) {
                    long weatherDate =
                            value.getAsLong(WeatherContract.WeatherEntry.COLUMN_DATE);
                    if (!SunshineDateUtils.isDateNormalized(weatherDate)) {
                        throw new IllegalArgumentException("Date must be normalized to insert");
                    }

                    long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, value);
                    if (_id != -1) {
                        rowsInserted++;
                    }
                }
                db.setTransactionSuccessful();
            } finally {
                db.endTransaction();
            }

            if (rowsInserted > 0) {
                getContext().getContentResolver().notifyChange(uri, null);
            }

            return rowsInserted;

        default:
            return super.bulkInsert(uri, values);
    }
}
 
Example 56
Project: FlickLauncher   File: IconCache.java   Source Code and License 5 votes vote down vote up
/**
 * Updates {@param values} to contain versoning information and adds it to the DB.
 * @param values {@link ContentValues} containing icon & title
 */
private void addIconToDB(ContentValues values, ComponentName key,
        PackageInfo info, long userSerial) {
    values.put(IconDB.COLUMN_COMPONENT, key.flattenToString());
    values.put(IconDB.COLUMN_USER, userSerial);
    values.put(IconDB.COLUMN_LAST_UPDATED, info.lastUpdateTime);
    values.put(IconDB.COLUMN_VERSION, info.versionCode);
    mIconDb.insertOrReplace(values);
}
 
Example 57
Project: AppsTimeline   File: DbHistoryExecutor.java   Source Code and License 5 votes vote down vote up
private ContentValues itemToContentValue(HistoryItem historyItem) {
    ContentValues values = new ContentValues();
    values.put(DbConst.TableHistory.FIELD_DATE, historyItem.mDate);
    values.put(DbConst.TableHistory.FIELD_DURATION, historyItem.mDuration);
    values.put(DbConst.TableHistory.FIELD_MOBILE_TRAFFIC, historyItem.mMobileTraffic);
    values.put(DbConst.TableHistory.FIELD_NAME, historyItem.mName);
    values.put(DbConst.TableHistory.FIELD_PACKAGE_NAME, historyItem.mPackageName);
    values.put(DbConst.TableHistory.FIELD_SYSTEM, historyItem.mIsSystem);
    values.put(DbConst.TableHistory.FIELD_TIMESTAMP, historyItem.mTimeStamp);
    return values;
}
 
Example 58
Project: Sprog-App   File: SprogDbHelper.java   Source Code and License 5 votes vote down vote up
public void removeFavoritePoem(String link) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.beginTransaction();

    ContentValues values = new ContentValues();
    db.delete(FAVORITES_TABLE, "link=?", new String[]{link});

    db.setTransactionSuccessful();
    db.endTransaction();
    db.close();
}
 
Example 59
Project: Cable-Android   File: MmsDatabase.java   Source Code and License 5 votes vote down vote up
public void markExpireStarted(long messageId, long startedTimestamp) {
  ContentValues contentValues = new ContentValues();
  contentValues.put(EXPIRE_STARTED, startedTimestamp);

  SQLiteDatabase db = databaseHelper.getWritableDatabase();
  db.update(TABLE_NAME, contentValues, ID_WHERE, new String[] {String.valueOf(messageId)});

  long threadId = getThreadIdForMessage(messageId);
  notifyConversationListeners(threadId);
}
 
Example 60
Project: WiFiSDCryptoLocker   File: SessionDaoImpl.java   Source Code and License 5 votes vote down vote up
@Override
public long insertSession(Session session) {
    ContentValues contentValues = new ContentValues();
    contentValues.put(COLUMN_NAME_ENCRYPTED_DATE, session.getEncryptedDate());
    contentValues.put(COLUMN_NAME_LOCATION, session.getLocation());
    contentValues.put(COLUMN_NAME_INITIALISATION_VECTOR, session.getIv());
    return sqLiteDatabase.insert(TABLE_NAME_SESSION, null, contentValues);
}