Example usage for android.database.sqlite SQLiteDatabase insertOrThrow

List of usage examples for android.database.sqlite SQLiteDatabase insertOrThrow

Introduction

In this page you can find the example usage for android.database.sqlite SQLiteDatabase insertOrThrow.

Prototype

public long insertOrThrow(String table, String nullColumnHack, ContentValues values) throws SQLException 

Source Link

Document

Convenience method for inserting a row into the database.

Usage

From source file:uk.org.rivernile.edinburghbustracker.android.SettingsDatabase.java

/**
 * Insert a new time alert in to the database. We have to store this because
 * it's not possible to get alarm information from the platform after we
 * have set up an alarm./*w  w  w  .j  a  v a2  s.  c  o  m*/
 * 
 * @param stopCode The stopCode for which the time alert is set.
 * @param serviceNames The names of the services which should trigger this
 * alert.
 * @param timeTrigger The time at which to trigger the time alert.
 */
public void insertNewTimeAlert(final String stopCode, final String[] serviceNames, final int timeTrigger) {
    final SQLiteDatabase db = getWritableDatabase();
    cleanupAlerts(db);

    int len = serviceNames.length;
    final StringBuilder sb = new StringBuilder();
    for (int i = 0; i < len; i++) {
        sb.append(serviceNames[i]);
        if (i != len - 1) {
            sb.append(',');
        }
    }

    final ContentValues cv = new ContentValues();
    cv.put(ALERTS_TYPE, ALERTS_TYPE_TIME);
    cv.put(ALERTS_TIME_ADDED, System.currentTimeMillis());
    cv.put(ALERTS_STOPCODE, stopCode);
    cv.put(ALERTS_SERVICE_NAMES, sb.toString());
    cv.put(ALERTS_TIME_TRIGGER, timeTrigger);

    db.insertOrThrow(ALERTS_TABLE, ALERTS_TIME_TRIGGER, cv);
}

From source file:org.kontalk.provider.UsersProvider.java

private Uri insertUser(ContentValues values, boolean offline, boolean discardName) {
    SQLiteDatabase db = dbHelper.getWritableDatabase();

    String table = offline ? TABLE_USERS_OFFLINE : TABLE_USERS;
    long id = 0;// w  w  w  .j  a va  2s .co m

    try {
        id = db.insertOrThrow(table, null, values);
    } catch (SQLException e) {
        String jid = values.getAsString(Users.JID);
        if (jid != null) {
            // discard display_name if requested
            if (discardName) {
                values.remove(Users.DISPLAY_NAME);
                values.remove(Users.NUMBER);
            }

            db.update(table, values, Users.JID + "=?", new String[] { jid });
        }
    }

    if (id >= 0)
        return ContentUris.withAppendedId(Users.CONTENT_URI, id);
    return null;
}

From source file:com.snt.bt.recon.database.DBHandler.java

public void addBleEntry(BluetoothLowEnergyEntry ble_entry) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_SESSION_ID, ble_entry.getSessionId().toString());
    values.put(KEY_LOCATION_ID, ble_entry.getLocationId().toString());
    values.put(KEY_TIMESTAMP, ble_entry.getTimestamp());
    values.put(KEY_MAC, ble_entry.getMac());
    values.put(KEY_RSSI, ble_entry.getRssi());
    values.put(KEY_DEVICE_NAME, ble_entry.getDeviceName());
    values.put(KEY_BLE_ADV_DATA, ble_entry.getBleAdvData());

    values.put(KEY_UPLOAD_STATUS, ble_entry.getUploadStatus());

    // Inserting Row
    db.insertOrThrow(TABLE_BLE, null, values);

    db.close(); // Closing database connection
}

From source file:com.snt.bt.recon.database.DBHandler.java

public void addBcEntry(BluetoothClassicEntry bc_entry) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_SESSION_ID, bc_entry.getSessionId().toString());
    values.put(KEY_LOCATION_ID, bc_entry.getLocationId().toString());
    values.put(KEY_TIMESTAMP, bc_entry.getTimestamp());
    values.put(KEY_MAC, bc_entry.getMac());
    values.put(KEY_TYPE, bc_entry.getType());
    values.put(KEY_RSSI, bc_entry.getRssi());
    values.put(KEY_DEVICE_NAME, bc_entry.getDeviceName());
    values.put(KEY_BC_CLASS, bc_entry.getBcClass());
    values.put(KEY_UPLOAD_STATUS, bc_entry.getUploadStatus());

    // Inserting Row
    db.insertOrThrow(TABLE_BC, null, values);
    //Log.d("DatabaseTest1", ""+test);

    db.close(); // Closing database connection
}

From source file:com.snt.bt.recon.database.DBHandler.java

public void addLocation(GPSLocation location) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_LOCATION_ID, location.getLocationId().toString());
    values.put(KEY_SESSION_ID, location.getSessionId().toString());
    values.put(KEY_TIMESTAMP, location.getTimestamp());
    values.put(KEY_LATITUDE, location.getLatitude());
    values.put(KEY_LONGITUDE, location.getLongitude());
    values.put(KEY_SPEED, location.getSpeed());
    values.put(KEY_BEARING, location.getBearing());
    values.put(KEY_ALTITUDE, location.getAltitude());
    values.put(KEY_ACCURACY, location.getAccuracy());
    values.put(KEY_UPLOAD_STATUS, location.getUploadStatus());

    // Inserting Row
    db.insertOrThrow(TABLE_LOCATIONS, null, values);

    db.close(); // Closing database connection
}

From source file:org.pixmob.freemobile.netstat.SyncServiceTesting.java

private String getDeviceId() {
    final SQLiteDatabase db = dbHelper.getWritableDatabase();
    String deviceId = null;/*from ww  w .  ja  va2s . c  o m*/
    Cursor deviceCursor = null;
    try {
        deviceCursor = db.query("device_testing", new String[] { "device_id" }, null, null, null, null, null);
        if (deviceCursor.moveToNext()) {
            deviceId = deviceCursor.getString(0);
        }
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    } finally {
        try {
            if (deviceCursor != null)
                deviceCursor.close();
        } catch (Exception e) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
    }
    if (deviceId == null) {
        // Generate a new device identifier.
        deviceId = UUID.randomUUID().toString();

        // Store this device identifier in the database.
        final ContentValues cv = new ContentValues(1);
        cv.put("device_id", deviceId);
        db.insertOrThrow("device_testing", null, cv);
    }
    return deviceId;
}

From source file:com.google.android.apps.santatracker.data.DestinationDbHelper.java

/**
 * Expects a writeable {@link SQLiteDatabase} - used for batch commits.
 *///  w w  w  . j a  va2 s  . c  o m
public void insertDestination(SQLiteDatabase db, String id, long arrivalTime, long departureTime, String city,
        String region, String country, double locationLat, double locationLng, long presentsDelivered,
        long presentsAtDestination, long timezone, long altitude, String photos, String weather,
        String streetView, String gmmStreetView) {

    ContentValues cv = new ContentValues();

    cv.put(COLUMN_NAME_IDENTIFIER, id);

    cv.put(COLUMN_NAME_ARRIVAL, arrivalTime);
    cv.put(COLUMN_NAME_DEPARTURE, departureTime);

    cv.put(COLUMN_NAME_CITY, city);
    cv.put(COLUMN_NAME_REGION, region);
    cv.put(COLUMN_NAME_COUNTRY, country);

    cv.put(COLUMN_NAME_LAT, locationLat);
    cv.put(COLUMN_NAME_LNG, locationLng);

    cv.put(COLUMN_NAME_PRESENTSDELIVERED, presentsDelivered);
    cv.put(COLUMN_NAME_PRESENTS_DESTINATION, presentsAtDestination);

    cv.put(COLUMN_NAME_TIMEZONE, timezone);
    cv.put(COLUMN_NAME_ALTITUDE, altitude);
    cv.put(COLUMN_NAME_PHOTOS, photos);
    cv.put(COLUMN_NAME_WEATHER, weather);
    cv.put(COLUMN_NAME_STREETVIEW, streetView);
    cv.put(COLUMN_NAME_GMMSTREETVIEW, gmmStreetView);

    // TODO: verify whether the db parameter is needed - can we just get
    // another writeable handle on the db (even if the transaction is
    // started on a different one?)
    db.insertOrThrow(TABLE_NAME, null, cv);
}

From source file:edu.mit.media.funf.pipeline.BasicPipeline.java

protected void writeData(String name, IJsonObject data) {

    SQLiteDatabase db = databaseHelper.getWritableDatabase();
    final double timestamp = data.get(ProbeKeys.BaseProbeKeys.TIMESTAMP).getAsDouble();
    final String value = data.toString();
    if (timestamp == 0L || name == null || value == null) {
        Log.e(LogUtil.TAG, "Unable to save data.  Not all required values specified. " + timestamp + " " + name
                + " - " + value);
        throw new SQLException("Not all required fields specified.");
    }//from   www  .  j  a  v  a2  s  . co m

    String[] subStrings = name.split("\\.");
    String probeName = subStrings[subStrings.length - 1];

    ContentValues cv = new ContentValues();
    cv.put(DatabaseHelper.TABLE_STANDARD_PROBE, name);
    cv.put(DatabaseHelper.TABLE_STANDARD_VALUE, data.toString());
    cv.put(DatabaseHelper.TABLE_STANDARD_TIMESTAMP, TimeUtil.alignedTimestamp);
    for (String entry : data.getAllKeys())
        if (DatabaseHelper.getAllowedList().contains(entry.toLowerCase(Locale.ENGLISH))) {
            String toSave = data.toString();
            try {
                toSave = data.get(entry).getAsString();
            } catch (Exception e) {
                e.printStackTrace();
            }
            cv.put(entry, toSave);
        }

    db.insertOrThrow(probeName, "", cv);

    Log.e("Database", name + " " + TimeUtil.alignedTimestamp);

    Intent intent = new Intent("pipeline");
    intent.putExtra("Name", name);
    intent.putExtra("IJsonObject", data.toString());
    // intent.setAction("edu.mit.media.funf.pipeline.broadcastreceiver");
    LocalBroadcastManager.getInstance(getFunfManager()).sendBroadcast(intent);
    db.close();
}

From source file:org.kontalk.provider.UsersProvider.java

private Uri insertOrUpdateKey(String jid, String fingerprint, ContentValues values, boolean insertOnly) {
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    if (jid == null || fingerprint == null)
        throw new IllegalArgumentException("either JID or fingerprint not provided");

    int rows = 0;

    try {/*from w w  w.java 2  s .c  o  m*/
        // try to insert the key with the provided values
        ContentValues insertValues = new ContentValues(values);
        insertValues.put(Keys.JID, jid);
        insertValues.put(Keys.FINGERPRINT, fingerprint);
        // use current timestamp if the caller didn't provide any
        long timestamp = values.containsKey(Keys.TIMESTAMP) ? values.getAsLong(Keys.TIMESTAMP)
                : System.currentTimeMillis();
        insertValues.put(Keys.TIMESTAMP, timestamp);
        db.insertOrThrow(TABLE_KEYS, null, insertValues);
        rows = 1;
    } catch (SQLiteConstraintException e) {
        if (!insertOnly) {
            // we got a duplicated key, update the requested values
            rows = db.update(TABLE_KEYS, values, Keys.JID + "=? AND " + Keys.FINGERPRINT + "=?",
                    new String[] { jid, fingerprint });
        }
    }

    if (rows >= 0)
        return Keys.CONTENT_URI.buildUpon().appendPath(jid).appendPath(fingerprint).build();
    return null;
}

From source file:org.qeo.android.service.ApplicationSecurity.java

/**
 * Insert allowed readers/writers into the database. Clear the mReadersWriters map when everything is saved in the
 * database.//w w  w  .jav a 2s . co  m
 */
private synchronized void insertReadersWriters() {
    SQLiteDatabase db = mService.getDatabase();

    // first delete all known readers/writers for this uid to ensure old ones get removed
    String where = TableManifestRW.C_UID + "=?";
    db.delete(TableManifestRW.NAME, where, new String[] { Integer.toString(mUid) });

    // add all
    for (Map.Entry<String, RW> entry : mReadersWriters.entrySet()) {
        ContentValues values = new ContentValues();
        values.put(TableManifestRW.C_NAME, entry.getKey());
        values.put(TableManifestRW.C_UID, mUid);
        values.put(TableManifestRW.C_PKG_NAME, mPkgName);
        LOG.fine("Add rw to table: " + entry.getKey() + " -- " + mUid + " -- " + mPkgName);
        switch (entry.getValue()) {
        case R: // read only
            values.put(TableManifestRW.C_READ, 1);
            values.put(TableManifestRW.C_WRITE, 0);
            break;
        case W: // write only
            values.put(TableManifestRW.C_READ, 0);
            values.put(TableManifestRW.C_WRITE, 1);
            break;
        case RW: // read/write only
            values.put(TableManifestRW.C_READ, 1);
            values.put(TableManifestRW.C_WRITE, 1);
            break;
        default:
            throw new IllegalStateException("value not handled");
        }
        db.insertOrThrow(TableManifestRW.NAME, null, values);
    }
    mReadersWriters.clear();
}