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

The following examples show how to use android.database.sqlite.SQLiteDatabase#insertOrThrow() .
Example 1
Project: iZhihu   File: ThumbnailsDatabase.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 增加到缓存列表中
 *
 * @param url
 * @return
 */
public boolean add(String url) {
    if (isCached(url)) {
        return false;
    }

    SQLiteDatabase db = new DatabaseOpenHelper(context).getWritableDatabase();
    try {
        ContentValues contentValues = new ContentValues();
        contentValues.put(COLUM_URL, url);

        long values = db.insertOrThrow(DATABASE_THUMBNAILS_TABLE_NAME, null, contentValues);
        return values > 1;
    } catch (SQLiteException e) {
        return false;
    } finally {
        db.close();
    }
}
 
Example 2
Project: Capstone-Project   File: PredatorDbHelper.java    License: MIT License 6 votes vote down vote up
public int addCollection(ContentValues contentValues) {
    // Create and/or open the database for writing
    SQLiteDatabase db = getWritableDatabase();

    // It's a good idea to wrap our insert in a transaction. This helps with performance and ensures
    // consistency of the database.
    db.beginTransaction();
    try {
        db.insertOrThrow(PredatorContract.CollectionsEntry.TABLE_NAME, null, contentValues);
        db.setTransactionSuccessful();
    } catch (Exception e) {
        Logger.e(TAG, "Error while trying to add collection to database", e);
    } finally {
        db.endTransaction();
    }
    return contentValues.getAsInteger(PredatorContract.CollectionsEntry.COLUMN_COLLECTION_ID);
}
 
Example 3
Project: restcomm-android-sdk   File: DatabaseManager.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public void addContact(String name, String uri) throws SQLException
{
   if (databaseHelper == null) {
      throw new RuntimeException("Database hasn't been opened.");
   }

   // Gets the data repository in write mode
   SQLiteDatabase db = databaseHelper.getWritableDatabase();

   // Create a new map of values, where column names are the keys
   ContentValues values = new ContentValues();

   values.put(DatabaseContract.ContactEntry.COLUMN_NAME_NAME, name);
   values.put(DatabaseContract.ContactEntry.COLUMN_NAME_URI, uri);
   db.insertOrThrow(DatabaseContract.ContactEntry.TABLE_NAME, null, values);
}
 
Example 4
Project: narrate-android   File: DataProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Uri insert(Uri uri, ContentValues values) {

    final int match = sUriMatcher.match(uri);
    SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();

    switch (match) {
        case ENTRIES: {
            db.insertOrThrow(Tables.ENTRIES, null, values);
            notifyChange(uri);
            return Entries.buildEntryUri(values.getAsString(Entries.UUID));
        }
        default: {
            throw new UnsupportedOperationException("Unknown insert uri: " + uri);
        }
    }
}
 
Example 5
Project: geopaparazzi   File: DaoNotes.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Add a note without transaction (for fast insert of many).
 *
 * @param lon            lon
 * @param lat            lat
 * @param altim          elevation
 * @param timestamp      the UTC timestamp in millis.
 * @param text           the text
 * @param description    a description.
 * @param form           the json form or null
 * @param sqliteDatabase the database reference.
 * @return the inserted note id.
 */
public static long addNoteNoTransaction(double lon, double lat, double altim, long timestamp, String text,
                                        String description, String form, String style, SQLiteDatabase sqliteDatabase) {
    ContentValues values = new ContentValues();
    values.put(NotesTableFields.COLUMN_LON.getFieldName(), lon);
    values.put(NotesTableFields.COLUMN_LAT.getFieldName(), lat);
    values.put(NotesTableFields.COLUMN_ALTIM.getFieldName(), altim);
    values.put(NotesTableFields.COLUMN_TS.getFieldName(), timestamp);
    if (description != null)
        values.put(NotesTableFields.COLUMN_DESCRIPTION.getFieldName(), description);
    values.put(NotesTableFields.COLUMN_TEXT.getFieldName(), text);
    if (form != null)
        values.put(NotesTableFields.COLUMN_FORM.getFieldName(), form);
    if (style != null)
        values.put(NotesTableFields.COLUMN_STYLE.getFieldName(), style);
    values.put(NotesTableFields.COLUMN_ISDIRTY.getFieldName(), 1);
    long noteId = sqliteDatabase.insertOrThrow(TABLE_NOTES, null, values);
    return noteId;
}
 
Example 6
Project: earth   File: EarthsProvider.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE " + EarthsContract.TABLE +
            " (" + EarthsContract.Columns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT" +
            ", " + EarthsContract.Columns.FILE + " TEXT" +
            ", " + EarthsContract.Columns.FETCHED_AT + " INTEGER" +
            ")");

    @SuppressWarnings("ConstantConditions") final LegacyEarthSharedState state
            = new LegacyEarthSharedState(getContext());

    if (!TextUtils.isEmpty(state.getLastEarth())) {
        ContentValues values = new ContentValues();

        values.put(EarthsContract.Columns.FILE, state.getLastEarth());
        values.put(EarthsContract.Columns.FETCHED_AT, System.currentTimeMillis());

        db.insertOrThrow(EarthsContract.TABLE, null, values);
    }
}
 
Example 7
Project: 4pdaClient-plus   File: TabTable.java    License: Apache License 2.0 5 votes vote down vote up
private static void saveTabInfo(SQLiteDatabase db, Themes topics, String template) {
    ContentValues values = new ContentValues();
    values.put(COLUMN_ID, -1);
    values.put(COLUMN_TEMPLATE, template);
    values.put(COLUMN_MAXCOUNT, topics.getThemesCount());
    db.insertOrThrow(TABLE_NAME, null, values);

}
 
Example 8
Project: QuantumFlux   File: QuantumFluxContentProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
    if (values.length == 0) return 0;

    TableDetails tableDetails = mUriMatcherHelper.getTableDetails(uri);
    SQLiteDatabase db = mDatabase.getWritableDatabase();

    if (mDebugEnabled) {
        QuantumFluxLog.d("********* Bulk Insert **********");
        QuantumFluxLog.d("Uri: " + uri);
    }

    int count = 0;

    try {
        db.beginTransactionNonExclusive();
        String tableName = tableDetails.getTableName();

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

            count++;
        }
        db.setTransactionSuccessful();

        notifyChanges(uri, tableDetails);
    } finally {
        db.endTransaction();
    }
    return count;
}
 
Example 9
Project: 4pdaClient-plus   File: ApplicationRelationsTable.java    License: Apache License 2.0 5 votes vote down vote up
public static void addRealtion(CharSequence packName, CharSequence topicId) {
    SQLiteDatabase db = null;

    try {
        DbHelper dbHelper = new DbHelper(App.getInstance());

        db = dbHelper.getWritableDatabase();
        String[] selectionArgs = new String[]{packName + "%"};
        db.execSQL("delete from " + TABLE_NAME + " where pack_name like ?", selectionArgs);

        ContentValues values = new ContentValues();
        values.put(COLUMN_ID, UUID.randomUUID().toString());
        values.put(COLUMN_PACK_NAME, packName.toString());
        values.put(COLUMN_APP_URL, topicId.toString());
        values.put(COLUMN_BYUSER_NAME, true);


        db.insertOrThrow(TABLE_NAME, null, values);

    } catch (Exception ex) {
        AppLog.e(App.getInstance(), ex);
    } finally {
        if (db != null) {
            // db.endTransaction();
            db.close();
        }
    }
}
 
Example 10
Project: earth   File: SettingsProvider.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE " + SettingsContract.TABLE +
            " (" + SettingsContract.Columns.INTERVAL + " INTEGER" +
            ", " + SettingsContract.Columns.RESOLUTION + " INTEGER" +
            ", " + SettingsContract.Columns.WIFI_ONLY + " INTEGER" +
            ", " + SettingsContract.Columns.DEBUG + " INTEGER" +
            ", " + SettingsContract.Columns.OFFSET_L + " REAL" +
            ", " + SettingsContract.Columns.OFFSET_S + " REAL" +
            ", " + SettingsContract.Columns.SCALE + " REAL DEFAULT 1" +
            ")");

    db.insertOrThrow(SettingsContract.TABLE, null,
            Settings.fromLegacySharedState(getContext()).toContentValues());
}
 
Example 11
Project: android-tv-leanback   File: AbstractVideoItemProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Uri insert(@NonNull Uri uri, ContentValues values) {
    final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    final int match = sUriMatcher.match(uri);
    switch (match) {
        case VIDEOITEM: {
            final long _id = db.insertOrThrow(Tables.VIDEO_ITEM, null, values);
            return VideoItemContract.VideoItem.buildItemUri(_id);
        }
        default: {
            throw new UnsupportedOperationException("Unknown uri: " + uri);
        }
    }
}
 
Example 12
Project: nextcloud-notes   File: NotesDatabase.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param url          URL to the root of the used Nextcloud instance without trailing slash
 * @param username     Username of the account
 * @param accountName  Composed by the username and the host of the URL, separated by @-sign
 * @param capabilities {@link Capabilities} object containing information about the brand colors, supported API versions, etc...
 * @throws SQLiteConstraintException in case accountName already exists
 */
public void addAccount(@NonNull String url, @NonNull String username, @NonNull String accountName, @NonNull Capabilities capabilities) throws SQLiteConstraintException {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues(4);
    values.put(key_url, url);
    values.put(key_username, username);
    values.put(key_account_name, accountName);
    values.put(key_capabilities_etag, capabilities.getETag());
    long accountId = db.insertOrThrow(table_accounts, null, values);
    updateBrand(accountId, capabilities);
}
 
Example 13
Project: android   File: Database.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Registra una ubicación en la Base de Datos
 */
public void nuevaUbicacion(Ubicacion ubicacion) {
   	
   	SQLiteDatabase db = this.getWritableDatabase();
   	
   	ContentValues valores = new ContentValues();
   	valores.put(NOMBRE, ubicacion.getNombre());
   	valores.put(LATITUD, ubicacion.getPosicion().latitude);
   	valores.put(LONGITUD, ubicacion.getPosicion().longitude);
   	db.insertOrThrow(TABLA, null, valores);
   }
 
Example 14
Project: CPOrm   File: CPOrmContentProvider.java    License: MIT License 5 votes vote down vote up
@Override
public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {

    int length = values.length;
    if (length == 0)
        return 0;

    TableDetails tableDetails = uriMatcherHelper.getTableDetails(uri);
    SQLiteDatabase db = database.getWritableDatabase();

    if (debugEnabled) {
        CPOrmLog.d("********* Bulk Insert **********");
        CPOrmLog.d("Uri: " + uri);
    }

    int count = 0;

    try {
        db.beginTransactionNonExclusive();
        String tableName = tableDetails.getTableName();
        for (int i = 0; i < length; i++) {

            db.insertOrThrow(tableName, null, values[i]);
            count++;

            if (count % 100 == 0)
                db.yieldIfContendedSafely();
        }

        db.setTransactionSuccessful();

        notifyChanges(uri.buildUpon().appendQueryParameter(PARAMETER_CHANGE_TYPE, CPOrm.ChangeType.INSERT.toString()).build(), tableDetails);
    } finally {
        db.endTransaction();
    }

    return count;
}
 
Example 15
Project: restcomm-android-sdk   File: DatabaseManager.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public void addMessage(String contactName, String messageText, boolean isLocal, String jobId, DatabaseContract.MessageDeliveryStatus deliveryStatus) throws SQLException
{
   if (databaseHelper == null) {
      throw new RuntimeException("Database hasn't been opened.");
   }

   // Gets the data repository in write mode
   SQLiteDatabase db = databaseHelper.getWritableDatabase();

   // Create a new map of values, where column names are the keys
   ContentValues values = new ContentValues();

   String type = "local";
   if (!isLocal) {
      type = "remote";
   }

   int contactId = getContactIdFromName(contactName);

   values.put(DatabaseContract.MessageEntry.COLUMN_NAME_CONTACT_ID, contactId);
   values.put(DatabaseContract.MessageEntry.COLUMN_NAME_TEXT, messageText);
   values.put(DatabaseContract.MessageEntry.COLUMN_NAME_TYPE, type);
   values.put(DatabaseContract.MessageEntry.COLUMN_NAME_JOB_ID, jobId);
   values.put(DatabaseContract.MessageEntry.COLUMN_NAME_DELIVERY_STATUS, deliveryStatus.ordinal());

   db.insertOrThrow(DatabaseContract.MessageEntry.TABLE_NAME, null, values);
}
 
Example 16
Project: Tanks   File: Table.java    License: MIT License 5 votes vote down vote up
public long insert(String entityName, T data)
{
  SQLiteDatabase database = helper.getWritableDatabase();
  ContentValues values = new ContentValues(2);
  values.put("Name", entityName);
  values.put("Data", Serializer.Serialize(data));

  return database.insertOrThrow(name, null, values);
}
 
Example 17
Project: make-your-app-material   File: ItemsProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Uri insert(@NonNull Uri uri, ContentValues values) {
    final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    final int match = sUriMatcher.match(uri);
    switch (match) {
        case ITEMS: {
            final long _id = db.insertOrThrow(Tables.ITEMS, null, values);
            mContext.getContentResolver().notifyChange(uri, null);
            return ItemsContract.Items.buildItemUri(_id);
        }
        default: {
            throw new UnsupportedOperationException("Unknown uri: " + uri);
        }
    }
}
 
Example 18
Project: LaunchEnr   File: LauncherProvider.java    License: GNU General Public License v3.0 4 votes vote down vote up
/**
 * Recreates workspace table and migrates data to the new table.
 */
boolean recreateWorkspaceTable(SQLiteDatabase db) {
    db.beginTransaction();
    try {
        Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
                new String[] {LauncherSettings.WorkspaceScreens._ID},
                null, null, null, null,
                LauncherSettings.WorkspaceScreens.SCREEN_RANK);
        ArrayList<Long> sortedIDs = new ArrayList<Long>();
        long maxId = 0;
        try {
            while (c.moveToNext()) {
                Long id = c.getLong(0);
                if (!sortedIDs.contains(id)) {
                    sortedIDs.add(id);
                    maxId = Math.max(maxId, id);
                }
            }
        } finally {
            c.close();
        }

        db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
        addWorkspacesTable(db, false);

        // Add all screen ids back
        int total = sortedIDs.size();
        for (int i = 0; i < total; i++) {
            ContentValues values = new ContentValues();
            values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
            values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
            addModifiedTime(values);
            db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
        }
        db.setTransactionSuccessful();
        mMaxScreenId = maxId;
    } catch (SQLException ex) {
        // Old version remains, which means we wipe old data
        ex.printStackTrace();
        return false;
    } finally {
        db.endTransaction();
    }
    return true;
}
 
Example 19
Project: Trebuchet   File: LauncherProvider.java    License: GNU General Public License v3.0 4 votes vote down vote up
/**
 * Recreates workspace table and migrates data to the new table.
 */
public boolean recreateWorkspaceTable(SQLiteDatabase db) {
    db.beginTransaction();
    try {
        Cursor c = db.query(TABLE_WORKSPACE_SCREENS,
                new String[] {LauncherSettings.WorkspaceScreens._ID},
                null, null, null, null,
                LauncherSettings.WorkspaceScreens.SCREEN_RANK);
        ArrayList<Long> sortedIDs = new ArrayList<Long>();
        long maxId = 0;
        try {
            while (c.moveToNext()) {
                Long id = c.getLong(0);
                if (!sortedIDs.contains(id)) {
                    sortedIDs.add(id);
                    maxId = Math.max(maxId, id);
                }
            }
        } finally {
            c.close();
        }

        db.execSQL("DROP TABLE IF EXISTS " + TABLE_WORKSPACE_SCREENS);
        addWorkspacesTable(db);

        // Add all screen ids back
        int total = sortedIDs.size();
        for (int i = 0; i < total; i++) {
            ContentValues values = new ContentValues();
            values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
            values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
            addModifiedTime(values);
            db.insertOrThrow(TABLE_WORKSPACE_SCREENS, null, values);
        }
        db.setTransactionSuccessful();
        mMaxScreenId = maxId;
    } catch (SQLException ex) {
        // Old version remains, which means we wipe old data
        Log.e(TAG, ex.getMessage(), ex);
        return false;
    } finally {
        db.endTransaction();
    }
    return true;
}
 
Example 20
Project: RedReader   File: RawObjectDB.java    License: GNU General Public License v3.0 3 votes vote down vote up
public synchronized void put(E object) {

		final SQLiteDatabase db = getWritableDatabase();

		try {
			final ContentValues values = new ContentValues(fields.length + 1);
			final long result = db.insertOrThrow(TABLE_NAME, null, toContentValues(object, values));

			if(result < 0) throw new RuntimeException("Database write failed");

		} catch(IllegalAccessException e) {
			throw new RuntimeException(e);

		} finally { db.close(); }
	}