Java Code Examples for android.database.sqlite.SQLiteDatabase.insert()

The following are Jave code examples for showing how to use insert() of the android.database.sqlite.SQLiteDatabase class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: AOSP-Kayboard-7.1.2   File: ActionBatch.java   View Source Code Vote up 7 votes
@Override
public void execute(final Context context) {
    if (null == mWordList) { // This should never happen
        Log.e(TAG, "MakeAvailableAction with a null word list!");
        return;
    }
    final SQLiteDatabase db = MetadataDbHelper.getDb(context, mClientId);
    if (null != MetadataDbHelper.getContentValuesByWordListId(db,
            mWordList.mId, mWordList.mVersion)) {
        Log.e(TAG, "Unexpected state of the word list '" + mWordList.mId + "' "
                + " for a makeavailable action. Marking as available anyway.");
    }
    DebugLogUtils.l("Making word list available : " + mWordList);
    // If mLocalFilename is null, then it's a remote file that hasn't been downloaded
    // yet, so we set the local filename to the empty string.
    final ContentValues values = MetadataDbHelper.makeContentValues(0,
            MetadataDbHelper.TYPE_BULK, MetadataDbHelper.STATUS_AVAILABLE,
            mWordList.mId, mWordList.mLocale, mWordList.mDescription,
            null == mWordList.mLocalFilename ? "" : mWordList.mLocalFilename,
            mWordList.mRemoteFilename, mWordList.mLastUpdate, mWordList.mRawChecksum,
            mWordList.mChecksum, mWordList.mRetryCount, mWordList.mFileSize,
            mWordList.mVersion, mWordList.mFormatVersion);
    PrivateLog.log("Insert 'available' record for " + mWordList.mDescription
            + " and locale " + mWordList.mLocale);
    db.insert(MetadataDbHelper.METADATA_TABLE_NAME, null, values);
}
 
Example 2
Project: GCSApp   File: DemoDBManager.java   View Source Code Vote up 7 votes
/**
 * save a message
 *
 * @param message
 * @return return cursor of the message
 */
public synchronized Integer saveMessage(InviteMessage message) {
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    int id = -1;
    if (db.isOpen()) {
        ContentValues values = new ContentValues();
        values.put(InviteMessgeDao.COLUMN_NAME_FROM, message.getFrom());
        values.put(InviteMessgeDao.COLUMN_NAME_GROUP_ID, message.getGroupId());
        values.put(InviteMessgeDao.COLUMN_NAME_GROUP_Name, message.getGroupName());
        values.put(InviteMessgeDao.COLUMN_NAME_REASON, message.getReason());
        values.put(InviteMessgeDao.COLUMN_NAME_TIME, message.getTime());
        values.put(InviteMessgeDao.COLUMN_NAME_STATUS, message.getStatus().ordinal());
        values.put(InviteMessgeDao.COLUMN_NAME_GROUPINVITER, message.getGroupInviter());
        db.insert(InviteMessgeDao.TABLE_NAME, null, values);

        Cursor cursor = db.rawQuery("select last_insert_rowid() from " + InviteMessgeDao.TABLE_NAME, null);
        if (cursor.moveToFirst()) {
            id = cursor.getInt(0);
        }

        cursor.close();
    }
    return id;
}
 
Example 3
Project: Trivia-Knowledge   File: DemoHelperClass.java   View Source Code Vote up 6 votes
public void insertRandomNumbers(int id,int one , int two ,int three , int four , int five) {
    ContentValues contentValues = new ContentValues();
    contentValues.put(ID,id);
    contentValues.put(ONE, one);
    contentValues.put(TWO, two);
    contentValues.put(THREE, three);
    contentValues.put(FOUR, four);
    contentValues.put(FIVE, five);

    SQLiteDatabase db = this.getWritableDatabase();
    db.beginTransaction();
    db.insert(TABLE_NAME4, null, contentValues);
    db.setTransactionSuccessful();
    db.endTransaction();
    db.close();
}
 
Example 4
Project: Retrospector-Android   File: RetroDbHelper.java   View Source Code Vote up 6 votes
public boolean insertMedia(Media media) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(Co_Media_Id,media.getId());
    contentValues.put(Co_Media_Title,media.getTitle());
    contentValues.put(Co_Media_Creator,media.getCreator());
    contentValues.put(Co_Media_Season,media.getSeason());
    contentValues.put(Co_Media_Episode,media.getEpisode());
    contentValues.put(Co_Media_Category,media.getCategory());
    contentValues.put(Co_Media_Description,media.getDescription());
    long result = db.insert(Tb_Media,null ,contentValues);
    if (result == -1)
        return false;

    int count = 0;
    for (Review review : media.getReviews())
        if (insertReview(review))
            count++;

    return true;
}
 
Example 5
Project: fussroll   File: DatabaseHandler.java   View Source Code Vote up 6 votes
void addLog(String userPhoneNumber, String category, String log, String meta, String localDate, String localTime, String utcDate, String utcTime, int logImage) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues contentValues = new ContentValues();
    contentValues.put(USER_PHONE_NUMBER, userPhoneNumber);
    contentValues.put(CATEGORY, category);
    contentValues.put(LOG, log);
    contentValues.put(META, meta);
    contentValues.put(LOCAL_DATE, localDate);
    contentValues.put(LOCAL_TIME, localTime);
    contentValues.put(UTC_DATE, utcDate);
    contentValues.put(UTC_TIME, utcTime);
    contentValues.put(LOG_IMAGE, logImage);

    db.insert(TABLE_ACTIVITIES, null, contentValues);
    db.close();
}
 
Example 6
Project: Trivia-Knowledge   File: DemoHelperClass.java   View Source Code Vote up 5 votes
public void InsertQid(int id) {
    ContentValues contentValues = new ContentValues();
    contentValues.put(CORRECTNO, id);
    SQLiteDatabase db = this.getWritableDatabase();
    db.beginTransaction();
    db.insert(TABLE_NAME2, null, contentValues);
    db.setTransactionSuccessful();
    db.endTransaction();
   /* Toast.makeText(context,"the answer was correct"+id+"was added",Toast.LENGTH_SHORT).show();*/
    db.close();
}
 
Example 7
Project: HiBangClient   File: PubMeHelpDB.java   View Source Code Vote up 5 votes
public void addCPubMeHelp(MyPubMeHelp msg) {
	SQLiteDatabase db = this.getWritableDatabase();
	ContentValues cv = new ContentValues();
	cv.put("id", getCount());
	cv.put("reqItemName", msg.getReqItemName());
	cv.put("helpUserID", msg.getHelpUserID());
	cv.put("reqItemID", msg.getReqItemID());
	cv.put("startTime", msg.getStartTime());
	cv.put("endTime", msg.getEndTime());
	db.insert(TABLE_NAME, null, cv);

}
 
Example 8
Project: BookWorldClient   File: BookManager.java   View Source Code Vote up 5 votes
public long insertBook(String title, String author, String subject,
                          String dateRead, int status) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(BOOK_COLUMN_TITLE, title);
    contentValues.put(BOOK_COLUMN_AUTHOR, author);
    contentValues.put(BOOK_COLUMN_SUBJECT, subject);
    contentValues.put(BOOK_COLUMN_DATE_READ, dateRead);
    contentValues.put(BOOK_COLUMN_STATUS, status);
    return db.insert("BOOK", null, contentValues);

}
 
Example 9
Project: CouponsTracker   File: CouponProvider.java   View Source Code Vote up 5 votes
@Nullable
@Override
public Uri insert(@NonNull Uri uri, ContentValues values) {
    DebugLog.logMethod();
    DebugLog.logMessage("Uri " + uri.toString());

    Uri returnUri;
    SQLiteDatabase writableDatabase = couponDbHelper.getWritableDatabase();
    switch (uriMatcher.match(uri)) {
        case COUPON: {
            DebugLog.logMessage("COUPON");
            long rowId = writableDatabase.insert(
                    CouponContract.CouponTable.TABLE_NAME,
                    null,
                    values
            );
            returnUri = CouponContract.CouponTable.makeUriForCoupon(rowId);
            break;
        }

        default: {
            throw new UnsupportedOperationException("Unknown URI:" + uri);
        }
    }

    notifyDataChange(uri);
    return returnUri;
}
 
Example 10
Project: quickblox-android   File: QbUsersDbManager.java   View Source Code Vote up 5 votes
public void saveUser(QBUser qbUser) {
    ContentValues cv = new ContentValues();
    DbHelper dbHelper = new DbHelper(mContext);
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    cv.put(DbHelper.DB_COLUMN_USER_FULL_NAME, qbUser.getFullName());
    cv.put(DbHelper.DB_COLUMN_USER_LOGIN, qbUser.getLogin());
    cv.put(DbHelper.DB_COLUMN_USER_ID, qbUser.getId());
    cv.put(DbHelper.DB_COLUMN_USER_PASSWORD, qbUser.getPassword());
    cv.put(DbHelper.DB_COLUMN_USER_TAG, qbUser.getTags().getItemsAsString());

    db.insert(DbHelper.DB_TABLE_NAME, null, cv);
    dbHelper.close();
}
 
Example 11
Project: programming   File: MyDBHandler.java   View Source Code Vote up 5 votes
public void addProduct (Products product){
    ContentValues values=new ContentValues();
    values.put(COLUMN_PRODUCTNAME,product.get_productname());
    SQLiteDatabase db=getWritableDatabase();
    db.insert(TABLE_PRODUCTS,null,values);
    db.close();

}
 
Example 12
Project: QueryLite   File: TableSqliteTest.java   View Source Code Vote up 5 votes
/**
 * Test columns order.
 */
@Test
public void columnsTest() {
    final SQLiteDatabase db = this.sqlite.getWritableDatabase();
    try {
        db.insert(TABLE, null, values("Jimmy"));
        final Cursor cursor = new TableSqlite(TABLE, db).cursor(
            Arrays.asList(COL_NAME, COL_ID),
            Collections.<WhereArg>emptyList(),
            Collections.<String>emptyList(),
            -1
        );
        try {
            MatcherAssert.assertThat(
                COL_NAME,
                cursor.getColumnName(0),
                Matchers.equalTo(COL_NAME)
            );
            MatcherAssert.assertThat(
                COL_ID,
                cursor.getColumnName(1),
                Matchers.equalTo(COL_ID)
            );
        } finally {
            cursor.close();
        }
    } finally {
        db.close();
    }
}
 
Example 13
Project: android-dev-challenge   File: WeatherProvider.java   View Source Code Vote up 5 votes
/**
 * 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 14
Project: GoUbiquitous   File: WeatherProvider.java   View Source Code Vote up 5 votes
/**
 * 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 15
Project: My-Day   File: DatabaseHandler.java   View Source Code Vote up 5 votes
public void addTask(DayTask task){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();

    values.put(VARS.TITLE, task.getTitle());
    values.put(VARS.DESCRIPTION, task.getDescription());
    values.put(VARS.DATE, task.getDate());
    values.put(VARS.STATUS, "false");
    values.put(VARS.TIME, task.getTime());

    db.insert(VARS.TABLE_NAME, null, values);
    Toast.makeText(context, "Task Added Successfully", Toast.LENGTH_SHORT).show();
    db.close();
}
 
Example 16
Project: CCDownload   File: DataSet.java   View Source Code Vote up 5 votes
public static void insertVideoPosition(String videoId, int position) {
	
	SQLiteDatabase database = sqLiteOpenHelper.getWritableDatabase();
	if (database.isOpen()) {
		ContentValues values = new ContentValues();
		values.put("videoId", videoId);
		values.put("position", position);
		database.insert(VIDEOPOSITION, null, values);
		database.close();
	}
}
 
Example 17
Project: Swface   File: DatabaseAdapter.java   View Source Code Vote up 5 votes
public void addLog_SignLog(SignLog log) {
	SQLiteDatabase db = databaseHelper.getWritableDatabase();
	ContentValues values = new ContentValues();

	values.put("object_id", log.getObjectId());
	values.put("user_name", log.getUser_name());
	values.put("confidence", log.getConfidence());
	values.put("time", log.getTime());
	db.insert(SignLogData.SignLogTable.TABLE_NAME, SignLogData.SignLogTable.TIME, values);
	db.close();
	Log.i(TAG, "addLog_SignLog: success");
}
 
Example 18
Project: GroupingMessages   File: DatabaseHelper.java   View Source Code Vote up 5 votes
private void createCategoryTable(SQLiteDatabase db) {
    db.execSQL(DatabaseContract.Category.CREATE_TABLE);

    ContentValues values = new ContentValues();
    values.put(DatabaseContract.Category.KEY_NAME, "Unknown");
    values.put(DatabaseContract.Category.KEY_COLOR, Color.WHITE);
    values.put(DatabaseContract.Category.KEY_VISIBILITY, 1);

    long addCatRowId = db.insert(DatabaseContract.Category.TABLE_NAME, null, values);

    if (addCatRowId == -1) {
        Log.e("GM/createDb", "Error while adding Unknown category");
    }
}
 
Example 19
Project: Shush   File: PlacesContentProvider.java   View Source Code Vote up 4 votes
/**
 * Handles request to insert a single new row of data.
 * @param uri
 * @param contentValues
 * @return
 */
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {

    //Get access to underlying database
    final SQLiteDatabase db = mPlacesDbHelper.getWritableDatabase();

    //Add a variable for uri matching and a uri for the new inserted row that can be returned
    int match = sUriMatcher.match(uri);
    Uri returnUri;

    switch (match){
        case PLACES:
            //insert new values to the database
            long id = db.insert(PlacesContract.PlaceEntry.TABLE_NAME,null,contentValues);
            if (id>0){
                returnUri = ContentUris.withAppendedId(uri,id);
            }
            else {
                throw new SQLException("Unable to insert row into " + uri);
            }
            break;
        //insert new values to the database
        case TIME:
            long timeId = db.insert(PlacesContract.TimeEntry.TABLE_NAME,null,contentValues);
            if (timeId>0){
                returnUri= ContentUris.withAppendedId(uri,timeId);
            }
            else{
                throw new SQLException("Unable to insert row into "+ uri);
            }
            break;
        //default case that throws exception
        default:
            throw  new UnsupportedOperationException("Unknown Uri : "+ uri);

    }

    // Notify the resolver if the uri has been changed, and return the newly inserted URI
    getContext().getContentResolver().notifyChange(uri,null);

    // Return constructed uri (this points to the newly inserted row of data)
    return returnUri;
}
 
Example 20
Project: Hello-Music-droid   File: SearchHistory.java   View Source Code Vote up 4 votes
public void addSearchString(final String searchString) {
    if (searchString == null) {
        return;
    }

    String trimmedString = searchString.trim();

    if (trimmedString.isEmpty()) {
        return;
    }

    final SQLiteDatabase database = mMusicDatabase.getWritableDatabase();
    database.beginTransaction();

    try {

        database.delete(SearchHistoryColumns.NAME,
                SearchHistoryColumns.SEARCHSTRING + " = ? COLLATE NOCASE",
                new String[]{trimmedString});

        final ContentValues values = new ContentValues(2);
        values.put(SearchHistoryColumns.SEARCHSTRING, trimmedString);
        values.put(SearchHistoryColumns.TIMESEARCHED, System.currentTimeMillis());
        database.insert(SearchHistoryColumns.NAME, null, values);

        Cursor oldest = null;
        try {
            database.query(SearchHistoryColumns.NAME,
                    new String[]{SearchHistoryColumns.TIMESEARCHED}, null, null, null, null,
                    SearchHistoryColumns.TIMESEARCHED + " ASC");

            if (oldest != null && oldest.getCount() > MAX_ITEMS_IN_DB) {
                oldest.moveToPosition(oldest.getCount() - MAX_ITEMS_IN_DB);
                long timeOfRecordToKeep = oldest.getLong(0);

                database.delete(SearchHistoryColumns.NAME,
                        SearchHistoryColumns.TIMESEARCHED + " < ?",
                        new String[]{String.valueOf(timeOfRecordToKeep)});

            }
        } finally {
            if (oldest != null) {
                oldest.close();
                oldest = null;
            }
        }
    } finally {
        database.setTransactionSuccessful();
        database.endTransaction();
    }
}