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

The following examples show how to use android.database.sqlite.SQLiteDatabase#insert() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Database.java    From candybar with Apache License 2.0 6 votes vote down vote up
public void addRequest(@Nullable SQLiteDatabase db, Request request) {
    SQLiteDatabase database = db;
    if (database == null) {
        if (!openDatabase()) {
            LogUtil.e("Database error: addRequest() failed to open database");
            return;
        }

        database = mDatabase.get().mSQLiteDatabase;
    }

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, request.getName());
    values.put(KEY_ACTIVITY, request.getActivity());

    String requestedOn = request.getRequestedOn();
    if (requestedOn == null) requestedOn = TimeHelper.getLongDateTime();
    values.put(KEY_REQUESTED_ON, requestedOn);

    database.insert(TABLE_REQUEST, null, values);
}
 
Example 2
Source File: DaoImpl.java    From Cangol-appcore with Apache License 2.0 6 votes vote down vote up
@Override
public int create(T paramT) throws SQLException {
    final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
    final SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
    long result = -1;
    try {
        db.beginTransaction();
        result = db.insert(mTableName, null, DatabaseUtils.getContentValues(paramT));
        db.setTransactionSuccessful();
    } catch (Exception e) {
        throw new SQLException(mTableName, e);
    } finally {
        db.endTransaction();
    }
    StrictMode.setThreadPolicy(oldPolicy);
    return (int) result;
}
 
Example 3
Source File: DBProxy.java    From android-orm with Apache License 2.0 6 votes vote down vote up
/**
 * 插入或者更新集合
 *
 * @param list
 * @param <T>
 */
public final <T extends IDColumn> void insertOrUpdate(List<T> list) {
    if (isEmpty(list)) {
        return;
    }
    ClassInfo<T> classInfo = getClassInfo(list.get(0));
    String tableName = classInfo.getTableName();
    SQLiteDatabase database = getDatabase();
    database.beginTransaction();
    for (T t : list) {
        ContentValues values = classInfo.getContentValues(t);
        if (values.size() > 0) {
            long primaryKey = t.getPrimaryId();
            if (primaryKey > 0) {
                database.update(tableName, values, IDColumn.PRIMARY_ID + "=" + primaryKey, null);
            } else {
                database.insert(tableName, null, values);
            }
        }
    }
    database.setTransactionSuccessful();
    database.endTransaction();
    close(database);
}
 
Example 4
Source File: AnalyticsDatabase.java    From braintree_android with MIT License 6 votes vote down vote up
public void addEvent(AnalyticsEvent request) {
    final ContentValues values = new ContentValues();
    values.put(EVENT, request.event);
    values.put(TIMESTAMP, request.timestamp);
    values.put(META_JSON, request.metadata.toString());

    DatabaseTask task = new DatabaseTask(new Runnable() {
        @Override
        public void run() {
            SQLiteDatabase db = null;
            try {
                db = getWritableDatabase();
                db.insert(TABLE_NAME, null, values);
            } catch (SQLiteException ignored) {
            } finally {
                if (db != null) {
                    db.close();
                }
            }
        }
    });

    queueTask(task);
}
 
Example 5
Source File: LockSettingsStorage.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public void writeKeyValue(SQLiteDatabase db, String key, String value, int userId) {
    ContentValues cv = new ContentValues();
    cv.put(COLUMN_KEY, key);
    cv.put(COLUMN_USERID, userId);
    cv.put(COLUMN_VALUE, value);

    db.beginTransaction();
    try {
        db.delete(TABLE, COLUMN_KEY + "=? AND " + COLUMN_USERID + "=?",
                new String[] {key, Integer.toString(userId)});
        db.insert(TABLE, null, cv);
        db.setTransactionSuccessful();
        mCache.putKeyValue(key, value, userId);
    } finally {
        db.endTransaction();
    }

}
 
Example 6
Source File: CapturedPlayerInfoProvider.java    From PADListener with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Uri insert(Uri uri, ContentValues values) {
	MyLog.entry("uri = " + uri);

	final SQLiteDatabase db = getDbHelper().getWritableDatabase();
	final CapturedPlayerInfoDescriptor.Paths path = CapturedPlayerInfoDescriptor.matchUri(uri);

	if (path == null) {
		throw new UnsupportedOperationException("URI : " + uri + " not supported.");
	}

	db.insert(CapturedPlayerInfoDescriptor.TABLE_NAME, null, values);
	getContext().getContentResolver().notifyChange(uri, null);

	MyLog.exit();
	return uri;
}
 
Example 7
Source File: LgcProvider.java    From live-group-chat with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Uri insert(Uri uri, ContentValues values) {
    SQLiteDatabase db = mOpenHelper.getWritableDatabase();

    int match = URI_MATCHER.match(uri);
    Uri retUri = null;
    switch (match) {
        case URI_MATCH_NOTIFICATION: {
            long rowID = db.insert(TABLE_NAMES[URI_MATCH_NOTIFICATION], "content", values);
            if (rowID > 0) {
                retUri = ContentUris.withAppendedId(NOTIFICATION_URI, rowID);
            }
            break;
        }

        default:
            throw new IllegalArgumentException("Unknown URL: " + uri);
    }

    if (retUri == null) {
        throw new IllegalArgumentException("Unknown URL: " + uri);
    }
    getContext().getContentResolver().notifyChange(retUri, null);

    return retUri;
}
 
Example 8
Source File: DownloadsDB.java    From UnityOBBDownloader with Apache License 2.0 6 votes vote down vote up
public boolean updateDownload(DownloadInfo di, ContentValues cv) {
    long id = di == null ? -1 : getIDForDownloadInfo(di);
    try {
        final SQLiteDatabase sqldb = mHelper.getWritableDatabase();
        if (id != -1) {
            if (1 != sqldb.update(DownloadColumns.TABLE_NAME,
                    cv, DownloadColumns._ID + " = " + id, null)) {
                return false;
            }
        } else {
            return -1 != sqldb.insert(DownloadColumns.TABLE_NAME,
                    DownloadColumns.URI, cv);
        }
    } catch (android.database.sqlite.SQLiteException ex) {
        ex.printStackTrace();
    }
    return false;
}
 
Example 9
Source File: CategoryHandler.java    From opentasks with Apache License 2.0 6 votes vote down vote up
/**
 * Check if a category with matching {@link ContentValues} exists and returns the existing category or creates a new category in the database.
 *
 * @param db
 *         The {@link SQLiteDatabase}.
 * @param values
 *         The {@link ContentValues} of the category.
 *
 * @return The {@link ContentValues} of the existing or new category.
 */
private ContentValues getOrInsertCategory(SQLiteDatabase db, ContentValues values)
{
    if (values.getAsBoolean(IS_NEW_CATEGORY))
    {
        // insert new category in category table
        ContentValues newCategoryValues = new ContentValues(4);
        newCategoryValues.put(Categories.ACCOUNT_NAME, values.getAsString(Categories.ACCOUNT_NAME));
        newCategoryValues.put(Categories.ACCOUNT_TYPE, values.getAsString(Categories.ACCOUNT_TYPE));
        newCategoryValues.put(Categories.NAME, values.getAsString(Category.CATEGORY_NAME));
        newCategoryValues.put(Categories.COLOR, values.getAsInteger(Category.CATEGORY_COLOR));

        long categoryID = db.insert(Tables.CATEGORIES, "", newCategoryValues);
        values.put(Category.CATEGORY_ID, categoryID);
    }

    // remove redundant values
    values.remove(IS_NEW_CATEGORY);
    values.remove(Categories.ACCOUNT_NAME);
    values.remove(Categories.ACCOUNT_TYPE);

    return values;
}
 
Example 10
Source File: AccountsDb.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
long insertExtra(long accountId, String key, String value) {
    SQLiteDatabase db = mDeDatabase.getWritableDatabaseUserIsUnlocked();
    ContentValues values = new ContentValues();
    values.put(EXTRAS_KEY, key);
    values.put(EXTRAS_ACCOUNTS_ID, accountId);
    values.put(EXTRAS_VALUE, value);
    return db.insert(CE_TABLE_EXTRAS, EXTRAS_KEY, values);
}
 
Example 11
Source File: Database.java    From ShaderEditor with MIT License 5 votes vote down vote up
public static long insertTexture(
		SQLiteDatabase db,
		String name,
		Bitmap bitmap,
		int thumbnailSize) {
	Bitmap thumbnail;

	try {
		thumbnail = Bitmap.createScaledBitmap(
				bitmap,
				thumbnailSize,
				thumbnailSize,
				true);
	} catch (IllegalArgumentException e) {
		return 0;
	}

	int w = bitmap.getWidth();
	int h = bitmap.getHeight();

	ContentValues cv = new ContentValues();
	cv.put(TEXTURES_NAME, name);
	cv.put(TEXTURES_WIDTH, w);
	cv.put(TEXTURES_HEIGHT, h);
	cv.put(TEXTURES_RATIO, calculateRatio(w, h));
	cv.put(TEXTURES_THUMB, bitmapToPng(thumbnail));
	cv.put(TEXTURES_MATRIX, bitmapToPng(bitmap));

	return db.insert(TEXTURES, null, cv);
}
 
Example 12
Source File: StateSimulations.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public void simulate(SchemaManager schemaManager) {
  SQLiteDatabase db = schemaManager.getWritableDatabase();
  Random rd = new Random();
  byte[] arr = new byte[7];
  rd.nextBytes(arr);

  ContentValues record = new ContentValues();
  record.put("backend_name", "b1");
  record.put("priority", PriorityMapping.toInt(Priority.DEFAULT));
  record.put("next_request_ms", 0);
  record.put("extras", arr);
  long contextId = db.insert("transport_contexts", null, record);
  assertThat(contextId).isNotEqualTo(-1);

  ContentValues values = new ContentValues();
  values.put("context_id", contextId);
  values.put("transport_name", "42");
  values.put("timestamp_ms", 1);
  values.put("uptime_ms", 2);
  values.put(
      "payload",
      new EncodedPayload(PROTOBUF_ENCODING, "Hello".getBytes(Charset.defaultCharset()))
          .getBytes());
  values.put("code", 1);
  values.put("num_attempts", 0);
  long newEventId = db.insert("events", null, values);
  assertThat(newEventId).isNotEqualTo(-1);

  ContentValues metadata = new ContentValues();
  metadata.put("event_id", newEventId);
  metadata.put("name", "key1");
  metadata.put("value", "value1");
  long metadataId = db.insert("event_metadata", null, metadata);
  assertThat(metadataId).isNotEqualTo(-1);
}
 
Example 13
Source File: DatabaseHandler.java    From repay-android with Apache License 2.0 5 votes vote down vote up
/**
 * Add a debt into the database, linked to a RepayID
 * @param repayID
 * @param amount
 * @param description
 * @throws android.database.SQLException
 * @throws NullPointerException
 */
public void addDebt(final String repayID, final BigDecimal amount, String description)
		throws SQLException, NullPointerException
{
	SQLiteDatabase db = this.getWritableDatabase();
	ContentValues values = new ContentValues();
	values.put(Names.D_REPAYID, repayID);
	values.put(Names.D_DATE, new Date().toString());
	values.put(Names.D_AMOUNT, amount.toString());
	values.put(Names.D_DESCRIPTION, description.replaceAll("[-+.^:,']",""));
	db.insert(Names.D_TABLENAME, null, values);
	db.close();
}
 
Example 14
Source File: DAOProgram.java    From fastnfitness with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @param m DBOProfil Profile a ajouter a la base
 */
public long add(Program m) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues value = new ContentValues();

    value.put(DAOProgram.NAME, m.getName());
    value.put(DAOProgram.DESCRIPTION, m.getDescription());

    long new_id = db.insert(DAOProgram.TABLE_NAME, null, value);

    close();
    return new_id;
}
 
Example 15
Source File: DatabaseHelper.java    From indigenous-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Saves a Timeline style.
 */
public void saveTimelineStyle(TimelineStyle t) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(TimelineStyle.COLUMN_TYPE, t.getType());
    values.put(TimelineStyle.COLUMN_CHANNEL_ID, t.getChannelId());

    db.delete(TimelineStyle.TABLE_NAME, TimelineStyle.COLUMN_CHANNEL_ID + "=?", new String[]{t.getChannelId()});
    db.insert(TimelineStyle.TABLE_NAME, null, values);

    db.close();
}
 
Example 16
Source File: LocalLogContentProvider.java    From nRF-Logger-API with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@SuppressWarnings("unused")
private long insertLog(final Uri uri, final ContentValues values) {
	mValues.clear();
	mValues.putAll(values);

	final SQLiteDatabase db = mLocalDatabaseHelper.get().getWritableDatabase();
	return db.insert(Tables.LOG, null, mValues);
}
 
Example 17
Source File: TopicDb.java    From tindroid with Apache License 2.0 4 votes vote down vote up
/**
 * Save topic description to DB
 *
 * @return ID of the newly added message
 */
public static long insert(SQLiteDatabase db, Topic topic) {
    BaseDb.Status status = topic.isNew() ? BaseDb.Status.QUEUED : BaseDb.Status.SYNCED;

    // Convert topic description to a map of values. If value is not set use a magical constant.
    // 1414213562373L is Oct 25, 2014 05:06:02.373 UTC, incidentally equal to the first few digits of sqrt(2)
    Date lastUsed = topic.getTouched() != null ? topic.getTouched() : new Date(1414213562373L);
    ContentValues values = new ContentValues();
    values.put(COLUMN_NAME_ACCOUNT_ID, BaseDb.getInstance().getAccountId());
    values.put(COLUMN_NAME_STATUS, status.value);
    values.put(COLUMN_NAME_TOPIC, topic.getName());

    values.put(COLUMN_NAME_CREATED, lastUsed.getTime());
    if (topic.getUpdated() != null) {
        // Updated is null at the topic creation time
        values.put(COLUMN_NAME_UPDATED, topic.getUpdated().getTime());
    }
    values.put(COLUMN_NAME_READ, topic.getRead());
    values.put(COLUMN_NAME_RECV, topic.getRecv());
    values.put(COLUMN_NAME_SEQ, topic.getSeq());
    values.put(COLUMN_NAME_CLEAR, topic.getClear());
    values.put(COLUMN_NAME_MAX_DEL, topic.getMaxDel());
    values.put(COLUMN_NAME_ACCESSMODE, BaseDb.serializeMode(topic.getAccessMode()));
    values.put(COLUMN_NAME_DEFACS, BaseDb.serializeDefacs(topic.getDefacs()));
    values.put(COLUMN_NAME_TAGS, BaseDb.serializeStringArray(topic.getTags()));
    if (topic.getLastSeen() != null) {
        values.put(COLUMN_NAME_LAST_SEEN, topic.getLastSeen().getTime());
    }
    if (topic.getLastSeenUA() != null) {
        values.put(COLUMN_NAME_LAST_SEEN_UA, topic.getLastSeenUA());
    }
    if (topic instanceof MeTopic) {
        values.put(COLUMN_NAME_CREDS, BaseDb.serialize(((MeTopic) topic).getCreds()));
    }
    values.put(COLUMN_NAME_PUBLIC, BaseDb.serialize(topic.getPub()));
    values.put(COLUMN_NAME_PRIVATE, BaseDb.serialize(topic.getPriv()));

    values.put(COLUMN_NAME_LASTUSED, lastUsed.getTime());
    values.put(COLUMN_NAME_MIN_LOCAL_SEQ, 0);
    values.put(COLUMN_NAME_MAX_LOCAL_SEQ, 0);
    values.put(COLUMN_NAME_NEXT_UNSENT_SEQ, UNSENT_ID_START);

    long id = db.insert(TABLE_NAME, null, values);
    if (id > 0) {
        StoredTopic st = new StoredTopic();
        st.id = id;
        st.lastUsed = lastUsed;
        st.nextUnsentId = UNSENT_ID_START;
        st.status = status;
        topic.setLocal(st);
    }

    return id;
}
 
Example 18
Source File: MessageDatabase.java    From weMessage with GNU Affero General Public License v3.0 4 votes vote down vote up
protected void addContact(Contact contact){
    SQLiteDatabase db = getWritableDatabase();
    db.insert(ContactTable.TABLE_NAME, null, contactToContentValues(contact));
}
 
Example 19
Source File: MonsterHunterDatabaseHelper.java    From MonsterHunter4UDatabase with MIT License 4 votes vote down vote up
public long insertRecord(SQLiteDatabase db, String table, ContentValues values) {
    long l = db.insert(table, null, values);
    return l;
}
 
Example 20
Source File: CategoryHandler.java    From opentasks-provider with Apache License 2.0 3 votes vote down vote up
/**
 * Inserts a relation entry in the database to link task and category.
 * 
 * @param db
 *            The {@link SQLiteDatabase}.
 * @param taskId
 *            The row id of the task.
 * @param categoryId
 *            The row id of the category.
 * @return The row id of the inserted relation.
 */
private long insertRelation(SQLiteDatabase db, long taskId, long categoryId, long propertyId)
{
	ContentValues relationValues = new ContentValues(3);
	relationValues.put(CategoriesMapping.TASK_ID, taskId);
	relationValues.put(CategoriesMapping.CATEGORY_ID, categoryId);
	relationValues.put(CategoriesMapping.PROPERTY_ID, propertyId);
	return db.insert(Tables.CATEGORIES_MAPPING, "", relationValues);
}