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:com.cloudmine.api.db.RequestDBOpenHelper.java

public void insertRequest(ContentValues requestValues, ContentValues[] headerValues) {
    SQLiteDatabase db = getWritableDatabase();
    db.beginTransaction();//from  w  ww.ja  va2s . c  o m
    try {
        long requestId = db.insertOrThrow(REQUEST_DATABASE_TABLE, null, requestValues);
        throwIfFailed(requestId);
        for (ContentValues headerValue : headerValues) {
            headerValue.put(KEY_HEADER_REQUEST_FK, requestId);
            long result = db.insertOrThrow(HEADER_DATABASE_TABLE, null, headerValue);
            throwIfFailed(result);
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}

From source file:com.odoo.support.provider.OContentProvider.java

@Override
public Uri insert(Uri uri, ContentValues initialValues) {
    reInitModel();/*from w ww .j a  v a2 s.  co m*/
    HashMap<String, List<Integer>> manyToManyIds = getManyToManyRecords(initialValues);
    final SQLiteDatabase db = model.getWritableDatabase();
    assert db != null;
    final int match = matcher.match(uri);
    Uri result;
    switch (match) {
    case COLLECTION:
        long id = db.insertOrThrow(model.getTableName(), null, initialValues);
        handleManyToMany(manyToManyIds, (int) id);
        result = Uri.parse(uri() + "/" + id);
        break;
    case SINGLE_ROW:
        throw new UnsupportedOperationException("Insert not supported on URI: " + uri);
    default:
        throw new UnsupportedOperationException("Unknown uri: " + uri);
    }
    // Send broadcast to registered ContentObservers, to refresh UI.
    Context ctx = getContext();
    assert ctx != null;
    ctx.getContentResolver().notifyChange(uri, null, false);
    return result;
}

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

/**
 * Insert a new favourite stop in to the database.
 *
 * @param stopCode The stop code to insert.
 * @param stopName The stop name to insert.
 * @throws SQLException If an error occurs whilst writing to the database.
 *//*  ww w. ja v  a 2 s .c  om*/
public void insertFavouriteStop(final String stopCode, final String stopName) throws SQLException {
    if (stopCode == null || stopName == null || stopCode.length() == 0 || stopName.length() == 0)
        return;
    if (getFavouriteStopExists(stopCode))
        return;
    final ContentValues cv = new ContentValues();
    cv.put(FAVOURITE_STOPS_STOPCODE, stopCode);
    cv.put(FAVOURITE_STOPS_STOPNAME, stopName);

    final SQLiteDatabase db = getWritableDatabase();
    db.insertOrThrow(FAVOURITE_STOPS_TABLE, FAVOURITE_STOPS_STOPNAME, cv);

    BackupManager.dataChanged(context.getPackageName());
}

From source file:com.jefftharris.passwdsafe.NotificationMgr.java

/** Enable notifications for the password file */
private void enablePasswdExpiryNotif(@NonNull PasswdFileData fileData, SQLiteDatabase db) throws SQLException {
    ContentValues values = new ContentValues(1);
    values.put(DB_COL_URIS_URI, fileData.getUri().toString());
    long id = db.insertOrThrow(DB_TABLE_URIS, null, values);
    doUpdatePasswdFileData(id, fileData, db);
}

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

/**
 * Insert a new proximity alert in to the database. We have to store this
 * because it's not possible to get information on proximity alerts we have
 * set back from the platform.//from   w ww .j a  va  2  s  .c o m
 * 
 * @param stopCode The stopCode for which the proximity alert is set.
 * @param distance The distance at which to trigger the proximity alert.
 */
public void insertNewProximityAlert(final String stopCode, final int distance) {
    final SQLiteDatabase db = getWritableDatabase();
    cleanupAlerts(db);

    final ContentValues cv = new ContentValues();
    cv.put(ALERTS_TYPE, ALERTS_TYPE_PROXIMITY);
    cv.put(ALERTS_TIME_ADDED, System.currentTimeMillis());
    cv.put(ALERTS_STOPCODE, stopCode);
    cv.put(ALERTS_DISTANCE_FROM, distance);

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

From source file:me.jreilly.JamesTweet.Adapters.TweetDataHelper.java

public Callback<List<Tweet>> callBackMaker(final int mMaxItems, final RecyclerView mRecyclerView,
        final Cursor mCursor, final SQLiteDatabase mTimelineDB, final TweetDataHelper mHelper,
        final SwipeRefreshLayout mSwipeRefreshLayout) {
    final int position = mCursor.getPosition();
    return new Callback<List<Tweet>>() {
        @Override/*ww w  .j  a va 2 s.  co m*/
        public void success(Result<List<Tweet>> listResult) {

            long numEntries = DatabaseUtils.queryNumEntries(mTimelineDB, "home");
            List<Tweet> list = listResult.data.subList(0, listResult.data.size());

            for (Tweet t : list) {
                try {
                    ContentValues tweetValues = mHelper.getValues(t);
                    mTimelineDB.insertOrThrow("home", null, tweetValues);
                    Log.v("NEW CONTEXT", "Added Tweet Tweets!");

                } catch (Exception te) {
                    Log.e("NEW CONTEXT", "Exception: " + te);
                }

            }

            int rowLimit = 50;

            if (DatabaseUtils.queryNumEntries(mTimelineDB, "home") > rowLimit) {
                String deleteQuery = "DELETE FROM home WHERE " + BaseColumns._ID + " NOT IN " + "(SELECT "
                        + BaseColumns._ID + " FROM home ORDER BY " + "update_time DESC " + "limit " + rowLimit
                        + ")";
                mTimelineDB.execSQL(deleteQuery);
                Log.v("NEW CONTEXT", "Deleteing Tweets!");
            }
            mRecyclerView.getAdapter().notifyDataSetChanged();
            if (mSwipeRefreshLayout != null) {
                mSwipeRefreshLayout.setRefreshing(false);
            } else {
                mRecyclerView.smoothScrollToPosition(position);
            }

            Log.v("NEW CONTEXT", "All done!");

        }

        @Override
        public void failure(TwitterException e) {
            Log.e("NEW CONTEXT", "Exception " + e);

        }
    };
}

From source file:com.raspi.chatapp.util.storage.MessageHistory.java

public void addChat(String buddyId, String name) {
    SQLiteDatabase db = mDbHelper.getWritableDatabase();
    int index = buddyId.indexOf('@');
    if (index >= 0) {
        buddyId = buddyId.substring(0, index);
    }//from   w  w w.  ja  v a 2 s.c  om
    index = name.indexOf('@');
    if (index >= 0) {
        name = name.substring(0, index);
    }
    ContentValues values = new ContentValues();
    values.put(MessageHistoryContract.ChatEntry.COLUMN_NAME_BUDDY_ID, buddyId);
    values.put(MessageHistoryContract.ChatEntry.COLUMN_NAME_NAME, name);
    try {
        db.insertOrThrow(MessageHistoryContract.ChatEntry.TABLE_NAME_ALL_CHATS,
                MessageHistoryContract.ChatEntry._ID, values);
    } catch (SQLException e) {
        Log.d("DATABASE", "Couldn't insert --> is already inserted.");
        return;
    } catch (Exception e) {
        Log.e("ERROR", "got an error while inserting a row into "
                + MessageHistoryContract.ChatEntry.TABLE_NAME_ALL_CHATS);
        return;
    }
    mDbHelper.createMessageTable(buddyId);
    db.close();
}

From source file:com.android.quicksearchbox.ShortcutRepositoryImplLog.java

@VisibleForTesting
void reportClickAtTime(SuggestionCursor suggestion, int position, long now) {
    suggestion.moveTo(position);/*from  ww w.ja v a  2  s .co m*/
    if (DBG) {
        Log.d(TAG, "logClicked(" + suggestion + ")");
    }

    if (SearchManager.SUGGEST_NEVER_MAKE_SHORTCUT.equals(suggestion.getShortcutId())) {
        if (DBG)
            Log.d(TAG, "clicked suggestion requested not to be shortcuted");
        return;
    }

    Corpus corpus = mCorpora.getCorpusForSource(suggestion.getSuggestionSource());
    if (corpus == null) {
        Log.w(TAG, "no corpus for clicked suggestion");
        return;
    }

    // Once the user has clicked on a shortcut, don't bother refreshing
    // (especially if this is a new shortcut)
    mRefresher.markShortcutRefreshed(suggestion.getSuggestionSource(), suggestion.getShortcutId());

    // Add or update suggestion info
    // Since intent_key is the primary key, any existing
    // suggestion with the same source+data+action will be replaced
    final ContentValues shortcut = makeShortcutRow(suggestion);
    String intentKey = shortcut.getAsString(Shortcuts.intent_key.name());

    // Log click for shortcut
    final ContentValues click = new ContentValues();
    click.put(ClickLog.intent_key.name(), intentKey);
    click.put(ClickLog.query.name(), suggestion.getUserQuery());
    click.put(ClickLog.hit_time.name(), now);
    click.put(ClickLog.corpus.name(), corpus.getName());

    runTransactionAsync(new SQLiteTransaction() {
        @Override
        protected boolean performTransaction(SQLiteDatabase db) {
            if (DBG)
                Log.d(TAG, "Adding shortcut: " + shortcut);
            db.replaceOrThrow(Shortcuts.TABLE_NAME, null, shortcut);
            db.insertOrThrow(ClickLog.TABLE_NAME, null, click);
            return true;
        }
    });
}

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

private String getDeviceId() {
    final SQLiteDatabase db = dbHelper.getWritableDatabase();
    final Cursor c = db.query("device", new String[] { "device_id" }, null, null, null, null, null);
    String deviceId = null;//from  www  .j a v  a 2  s .  c  om
    try {
        if (c.moveToNext()) {
            deviceId = c.getString(0);
        }
    } finally {
        c.close();
    }
    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", null, cv);
    }
    return deviceId;
}

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

public void addTrip(Trip trip) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_SESSION_ID, trip.getSessionId().toString());
    values.put(KEY_IMEI, trip.getImei());
    values.put(KEY_TRANSPORT, trip.getTransport());

    values.put(KEY_TIMESTAMP_START, trip.getTimestampStart());
    values.put(KEY_TIMESTAMP_END, trip.getTimestampEnd());
    values.put(KEY_APP_VERSION, trip.getAppVersion());

    values.put(KEY_UPLOAD_STATUS, trip.getUploadStatus());
    // Inserting Row
    db.insertOrThrow(TABLE_TRIPS, null, values);
    db.close(); // Closing database connection
}