Example usage for android.database.sqlite SQLiteDatabase insert

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

Introduction

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

Prototype

public long insert(String table, String nullColumnHack, ContentValues values) 

Source Link

Document

Convenience method for inserting a row into the database.

Usage

From source file:com.sonetel.db.DBProvider.java

@Override
public Uri insert(Uri uri, ContentValues initialValues) {
    int matched = URI_MATCHER.match(uri);
    String matchedTable = null;/*  w  w w .  ja v a  2  s  .c o  m*/
    Uri baseInsertedUri = null;
    switch (matched) {
    case ACCOUNTS:
    case ACCOUNTS_ID:
        matchedTable = SipProfile.ACCOUNTS_TABLE_NAME;
        baseInsertedUri = SipProfile.ACCOUNT_ID_URI_BASE;
        break;
    case CALLLOGS:
    case CALLLOGS_ID:
        matchedTable = SipManager.CALLLOGS_TABLE_NAME;
        baseInsertedUri = SipManager.CALLLOG_ID_URI_BASE;
        break;
    case FILTERS:
    case FILTERS_ID:
        matchedTable = SipManager.FILTERS_TABLE_NAME;
        baseInsertedUri = SipManager.FILTER_ID_URI_BASE;
        break;
    case MESSAGES:
    case MESSAGES_ID:
        matchedTable = SipMessage.MESSAGES_TABLE_NAME;
        baseInsertedUri = SipMessage.MESSAGE_ID_URI_BASE;
        break;
    case ACCESSNO:
        matchedTable = SipProfile.ACCESS_NUMS_TABLE_NAME;
        baseInsertedUri = SipProfile.ACCESS_URI_BASE;
        break;
    case ACCOUNTS_STATUS_ID:
        long id = ContentUris.parseId(uri);
        synchronized (profilesStatus) {
            SipProfileState ps = new SipProfileState();
            if (profilesStatus.containsKey(id)) {
                ContentValues currentValues = profilesStatus.get(id);
                ps.createFromContentValue(currentValues);
            }
            ps.createFromContentValue(initialValues);
            ContentValues cv = ps.getAsContentValue();
            cv.put(SipProfileState.ACCOUNT_ID, id);
            profilesStatus.put(id, cv);
            Log.d(THIS_FILE, "Added " + cv);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return uri;
    default:
        break;
    }

    if (matchedTable == null) {
        throw new IllegalArgumentException(UNKNOWN_URI_LOG + uri);
    }

    ContentValues values;

    if (initialValues != null) {
        values = new ContentValues(initialValues);
    } else {
        values = new ContentValues();
    }

    SQLiteDatabase db = mOpenHelper.getWritableDatabase();

    long rowId = db.insert(matchedTable, null, values);

    // If the insert succeeded, the row ID exists.
    if (rowId >= 0) {
        // TODO : for inserted account register it here

        Uri retUri = ContentUris.withAppendedId(baseInsertedUri, rowId);
        getContext().getContentResolver().notifyChange(retUri, null);

        if (matched == ACCOUNTS || matched == ACCOUNTS_ID) {
            broadcastAccountChange(rowId);
        }
        if (matched == CALLLOGS || matched == CALLLOGS_ID) {
            db.delete(SipManager.CALLLOGS_TABLE_NAME,
                    CallLog.Calls._ID + " IN " + "(SELECT " + CallLog.Calls._ID + " FROM "
                            + SipManager.CALLLOGS_TABLE_NAME + " ORDER BY " + CallLog.Calls.DEFAULT_SORT_ORDER
                            + " LIMIT -1 OFFSET 500)",
                    null);
        }
        if (matched == ACCOUNTS_STATUS || matched == ACCOUNTS_STATUS_ID) {
            broadcastRegistrationChange(rowId);
        }
        if (matched == FILTERS || matched == FILTERS_ID) {
            Filter.resetCache();
        }

        return retUri;
    }

    throw new SQLException("Failed to insert row into " + uri);
}

From source file:com.alchemiasoft.common.content.BookDBOpenHelper.java

@Override
public void onCreate(SQLiteDatabase db) {
    try {/*from w  w  w  .  j a  v  a  2s . c o m*/
        db.beginTransaction();

        db.execSQL(BookDB.Book.CREATE_TABLE);

        String input = null;
        try {
            input = ResUtil.assetAsString(mContext, Constants.BOOKS_PATH);
        } catch (Exception e) {
            Log.e(TAG_LOG, "Cannot read the input at assets/" + Constants.BOOKS_PATH);
        }
        // Adding the default entries
        if (!TextUtils.isEmpty(input)) {
            Log.d(TAG_LOG, "Adding into the DB: " + input);
            final JSONArray arr = new JSONArray(input);
            final List<Book> books = Book.allFrom(arr);
            // Adding the all the books as a batch
            for (final Book book : books) {
                db.insert(BookDB.Book.TABLE, null, book.toValues());
            }
        }

        db.setTransactionSuccessful();
        Log.i(TAG_LOG, "Successfully created " + BookDB.NAME);
    } catch (Exception e) {
        Log.e(TAG_LOG, "Error creating " + BookDB.NAME + ": ", e);
    } finally {
        db.endTransaction();
    }
}

From source file:de.stadtrallye.rallyesoft.model.Server.java

public void writeUsers(List<GroupUser> users) {
    Log.v(THIS, "Saving Users");

    final SQLiteDatabase db = Storage.getDatabaseProvider().getDatabase();

    db.delete(Users.TABLE, null, null);/*from w  w w  .ja  va 2 s .  c o  m*/

    for (GroupUser u : users) {
        ContentValues insert = new ContentValues();
        insert.put(Users.KEY_ID, u.userID);
        insert.put(Users.KEY_NAME, u.name);
        insert.put(Users.FOREIGN_GROUP, u.groupID);
        db.insert(Users.TABLE, null, insert);
    }
}

From source file:de.stadtrallye.rallyesoft.model.Server.java

private void writeGroups() {
    Log.v(THIS, "Saving Groups:" + groups);

    final SQLiteDatabase db = Storage.getDatabaseProvider().getDatabase();
    db.delete(Groups.TABLE, null, null);

    for (Group g : groups) {
        ContentValues insert = new ContentValues();
        insert.put(Groups.KEY_ID, g.groupID);
        insert.put(Groups.KEY_NAME, g.name);
        insert.put(Groups.KEY_DESCRIPTION, g.description);
        db.insert(Groups.TABLE, null, insert);
    }// www  .  j  av a  2  s. c om
}

From source file:org.thomnichols.android.gmarks.GmarksProvider.java

@Override
public Uri insert(Uri uri, ContentValues initialValues) {
    // Validate the requested uri
    if (sUriMatcher.match(uri) != BOOKMARKS_URI) {
        throw new IllegalArgumentException("Unknown URI " + uri);
    }// w  ww .j av a2 s  . c  o m

    ContentValues values;
    if (initialValues != null) {
        values = new ContentValues(initialValues);
    } else {
        values = new ContentValues();
    }

    Long now = Long.valueOf(System.currentTimeMillis());

    // Make sure that the fields are all set
    if (values.containsKey(Bookmark.Columns.CREATED_DATE) == false) {
        values.put(Bookmark.Columns.CREATED_DATE, now);
    }

    if (values.containsKey(Bookmark.Columns.MODIFIED_DATE) == false) {
        values.put(Bookmark.Columns.MODIFIED_DATE, now);
    }

    if (values.containsKey(Bookmark.Columns.TITLE) == false) {
        Resources r = Resources.getSystem();
        values.put(Bookmark.Columns.TITLE, r.getString(android.R.string.untitled));
    }

    if (values.containsKey(Bookmark.Columns.DESCRIPTION) == false) {
        values.put(Bookmark.Columns.DESCRIPTION, "");
    }

    SQLiteDatabase db = dbHelper.getWritableDatabase();
    long rowId = db.insert(BOOKMARKS_TABLE_NAME, "", values);
    if (rowId > 0) {
        Uri noteUri = ContentUris.withAppendedId(Bookmark.CONTENT_URI, rowId);
        getContext().getContentResolver().notifyChange(noteUri, null);
        return noteUri;
    }

    throw new SQLException("Failed to insert row into " + uri);
}

From source file:com.csipsimple.db.DBProvider.java

@Override
public Uri insert(Uri uri, ContentValues initialValues) {
    int matched = URI_MATCHER.match(uri);
    String matchedTable = null;// w  ww.  ja v  a2  s .c  om
    Uri baseInsertedUri = null;

    switch (matched) {
    case ACCOUNTS:
    case ACCOUNTS_ID:
        matchedTable = SipProfile.ACCOUNTS_TABLE_NAME;
        baseInsertedUri = SipProfile.ACCOUNT_ID_URI_BASE;
        break;
    case CALLLOGS:
    case CALLLOGS_ID:
        matchedTable = SipManager.CALLLOGS_TABLE_NAME;
        baseInsertedUri = SipManager.CALLLOG_ID_URI_BASE;
        break;
    case FILTERS:
    case FILTERS_ID:
        matchedTable = SipManager.FILTERS_TABLE_NAME;
        baseInsertedUri = SipManager.FILTER_ID_URI_BASE;
        break;
    case MESSAGES:
    case MESSAGES_ID:
        matchedTable = SipMessage.MESSAGES_TABLE_NAME;
        baseInsertedUri = SipMessage.MESSAGE_ID_URI_BASE;
        break;
    case ACCOUNTS_STATUS_ID:
        long id = ContentUris.parseId(uri);
        synchronized (profilesStatus) {
            SipProfileState ps = new SipProfileState();
            if (profilesStatus.containsKey(id)) {
                ContentValues currentValues = profilesStatus.get(id);
                ps.createFromContentValue(currentValues);
            }
            ps.createFromContentValue(initialValues);
            ContentValues cv = ps.getAsContentValue();
            cv.put(SipProfileState.ACCOUNT_ID, id);
            profilesStatus.put(id, cv);
            Log.d(THIS_FILE, "Added " + cv);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return uri;
    default:
        break;
    }

    if (matchedTable == null) {
        throw new IllegalArgumentException(UNKNOWN_URI_LOG + uri);
    }

    ContentValues values;

    if (initialValues != null) {
        values = new ContentValues(initialValues);
    } else {
        values = new ContentValues();
    }

    SQLiteDatabase db = mOpenHelper.getWritableDatabase();

    long rowId = db.insert(matchedTable, null, values);

    // If the insert succeeded, the row ID exists.
    if (rowId >= 0) {
        // TODO : for inserted account register it here

        Uri retUri = ContentUris.withAppendedId(baseInsertedUri, rowId);
        getContext().getContentResolver().notifyChange(retUri, null);

        if (matched == ACCOUNTS || matched == ACCOUNTS_ID) {
            broadcastAccountChange(rowId);
        }
        if (matched == CALLLOGS || matched == CALLLOGS_ID) {
            db.delete(SipManager.CALLLOGS_TABLE_NAME,
                    CallLog.Calls._ID + " IN " + "(SELECT " + CallLog.Calls._ID + " FROM "
                            + SipManager.CALLLOGS_TABLE_NAME + " ORDER BY " + CallLog.Calls.DEFAULT_SORT_ORDER
                            + " LIMIT -1 OFFSET 500)",
                    null);
        }
        if (matched == ACCOUNTS_STATUS || matched == ACCOUNTS_STATUS_ID) {
            broadcastRegistrationChange(rowId);
        }
        if (matched == FILTERS || matched == FILTERS_ID) {
            Filter.resetCache();
        }

        return retUri;
    }

    throw new SQLException("Failed to insert row into " + uri);
}

From source file:com.qi.airstat.BluetoothLeService.java

private void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic) {
    final Intent intent = new Intent(action);

    int signal = 0;

    // This is special handling for the Heart Rate Measurement profile.  Data parsing is
    // carried out as per profile specifications:
    // http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
    if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
        int flag = characteristic.getProperties();
        int format = -1;
        if ((flag & 0x01) != 0) {
            format = BluetoothGattCharacteristic.FORMAT_UINT16;
            Log.d(TAG, "Heart rate format UINT16.");
        } else {/* w  ww.  ja va2  s.  c  o m*/
            format = BluetoothGattCharacteristic.FORMAT_UINT8;
            Log.d(TAG, "Heart rate format UINT8.");
        }

        final int heartRate = characteristic.getIntValue(format, 1);
        signal = heartRate;
        Log.d(TAG, String.format("Received heart rate: %d", heartRate));
        intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
    } else {
        // For all other profiles, writes the data formatted in HEX.
        final byte[] data = characteristic.getValue();
        if (data != null && data.length > 0) {
            final StringBuilder stringBuilder = new StringBuilder(data.length);
            for (byte byteChar : data)
                stringBuilder.append(String.format("%02X ", byteChar));
            intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());

            signal = Integer.parseInt(new String(data));
        }
    }

    DatabaseManager databaseManager = new DatabaseManager(BluetoothLeService.this);
    SQLiteDatabase database = databaseManager.getWritableDatabase();

    ContentValues values = new ContentValues();
    String date = new SimpleDateFormat("yyMMddHHmmss").format(new java.util.Date());

    values.put(Constants.DATABASE_COMMON_COLUMN_TIME_STAMP, date);
    values.put(Constants.DATABASE_HEART_RATE_COLUMN_HEART_RATE, signal);
    database.insert(Constants.DATABASE_HEART_RATE_TABLE, null, values);

    database.close();

    try {
        Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        latitude = location.getLatitude();
        longitude = location.getLongitude();
    } catch (SecurityException exception) {
        exception.printStackTrace();
    }

    JSONObject reformedObject = new JSONObject();
    JSONArray reformedArray = new JSONArray();

    try {
        JSONObject item = new JSONObject();
        item.put("timeStamp", date);
        item.put("connectionID", Constants.CID_BLE);
        item.put("heartrate", signal);
        item.put("latitude", latitude);
        item.put("longitude", longitude);

        reformedArray.put(item);
        reformedObject.put("HR", reformedArray);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    HttpService httpService = new HttpService();
    String responseCode = httpService.executeConn(null, "POST",
            "http://teamc-iot.calit2.net/IOT/public/rcv_json_data", reformedObject);

    sendBroadcast(intent);
}

From source file:org.noorganization.instalistsynch.controller.local.dba.impl.SqliteGroupAccessDbControllerTest.java

License:asdf

public void testHasIdInDatabase() throws Exception {
    Date currentDate = new Date();
    SQLiteDatabase db = mDbHelper.getWritableDatabase();

    ContentValues cv = new ContentValues();
    cv.put(GroupAccess.COLUMN.GROUP_ID, 1);
    cv.put(GroupAccess.COLUMN.INTERRUPTED, false);
    cv.put(GroupAccess.COLUMN.SYNCHRONIZE, true);
    cv.put(GroupAccess.COLUMN.LAST_UPDATE_FROM_SERVER, ISO8601Utils.format(currentDate));
    cv.put(GroupAccess.COLUMN.LAST_TOKEN_REQUEST, ISO8601Utils.format(currentDate));
    cv.put(GroupAccess.COLUMN.TOKEN, "fdskhbvvkddscddueFSNDFSAdnandk3229df-dFSJDKMds.");

    assertTrue(db.insert(GroupAccess.TABLE_NAME, null, cv) >= 0);

    assertTrue(mGroupAuthAccessDbController.hasIdInDatabase(1));
    assertFalse(mGroupAuthAccessDbController.hasIdInDatabase(2));

}

From source file:org.noorganization.instalistsynch.controller.local.dba.impl.SqliteGroupAccessDbControllerTest.java

License:asdf

public void testGetGroupAuthAccess() throws Exception {
    Date currentDate = new Date();
    SQLiteDatabase db = mDbHelper.getWritableDatabase();

    ContentValues cv = new ContentValues();
    cv.put(GroupAccess.COLUMN.GROUP_ID, 1);
    cv.put(GroupAccess.COLUMN.INTERRUPTED, false);
    cv.put(GroupAccess.COLUMN.SYNCHRONIZE, true);
    cv.put(GroupAccess.COLUMN.LAST_UPDATE_FROM_SERVER, ISO8601Utils.format(currentDate));
    cv.put(GroupAccess.COLUMN.LAST_TOKEN_REQUEST, ISO8601Utils.format(currentDate));
    cv.put(GroupAccess.COLUMN.TOKEN, "fdskhbvvkddscddueFSNDFSAdnandk3229df-dFSJDKMds.");

    assertTrue(db.insert(GroupAccess.TABLE_NAME, null, cv) >= 0);

    GroupAccess groupAccess = mGroupAuthAccessDbController.getGroupAuthAccess(1);
    assertNotNull(groupAccess);/*from   www .  j  a v a2s  .  c  om*/
    assertEquals(1, groupAccess.getGroupId());
    assertEquals(false, groupAccess.wasInterrupted());
    assertEquals(true, groupAccess.isSynchronize());
    assertEquals(ISO8601Utils.format(currentDate), ISO8601Utils.format(groupAccess.getLastUpdateFromServer()));
    assertEquals(ISO8601Utils.format(currentDate), ISO8601Utils.format(groupAccess.getLastTokenRequest()));
    assertEquals("fdskhbvvkddscddueFSNDFSAdnandk3229df-dFSJDKMds.", groupAccess.getToken());
}