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:org.opendatakit.common.android.provider.impl.FormsProviderImpl.java

@Override
public synchronized Uri insert(Uri uri, ContentValues initialValues) {
    List<String> segments = uri.getPathSegments();

    if (segments.size() != 1) {
        throw new IllegalArgumentException("Unknown URI (too many segments!) " + uri);
    }/*from www  .  ja va2  s .co  m*/

    String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);
    WebLogger log = WebLogger.getLogger(appName);

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

    // ODK2: require FORM_MEDIA_PATH (different behavior -- ODK1 and
    // required FORM_FILE_PATH)
    if (!values.containsKey(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)) {
        throw new IllegalArgumentException(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + " must be specified.");
    }

    // Normalize path...
    File mediaPath = ODKFileUtils.asAppFile(appName,
            values.getAsString(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH));

    // require that the form directory actually exists
    if (!mediaPath.exists()) {
        throw new IllegalArgumentException(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH
                + " directory does not exist: " + mediaPath.getAbsolutePath());
    }

    patchUpValues(appName, values);

    if (values.containsKey(FormsColumns.DISPLAY_SUBTEXT) == false) {
        Date today = new Date();
        String ts = new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time),
                Locale.getDefault()).format(today);
        values.put(FormsColumns.DISPLAY_SUBTEXT, ts);
    }

    if (values.containsKey(FormsColumns.DISPLAY_NAME) == false) {
        values.put(FormsColumns.DISPLAY_NAME, mediaPath.getName());
    }

    // first try to see if a record with this filename already exists...
    String[] projection = { FormsColumns.FORM_ID, FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH };
    String[] selectionArgs = { ODKFileUtils.asRelativePath(appName, mediaPath) };
    String selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "=?";
    Cursor c = null;

    SQLiteDatabase db = null;
    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        db.beginTransaction();
        try {
            c = db.query(DatabaseConstants.FORMS_TABLE_NAME, projection, selection, selectionArgs, null, null,
                    null);
            if (c == null) {
                throw new SQLException("FAILED Insert into " + uri
                        + " -- unable to query for existing records: " + mediaPath.getAbsolutePath());
            }
            if (c.getCount() > 0) {
                // already exists
                throw new SQLException("FAILED Insert into " + uri
                        + " -- row already exists for form directory: " + mediaPath.getAbsolutePath());
            }
        } catch (Exception e) {
            log.w(t, "FAILED Insert into " + uri + " -- query for existing row failed: " + e.toString());

            if (e instanceof SQLException) {
                throw (SQLException) e;
            } else {
                throw new SQLException(
                        "FAILED Insert into " + uri + " -- query for existing row failed: " + e.toString());
            }
        } finally {
            if (c != null) {
                c.close();
            }
        }

        try {
            long rowId = db.insert(DatabaseConstants.FORMS_TABLE_NAME, null, values);
            db.setTransactionSuccessful();
            if (rowId > 0) {
                Uri formUri = Uri.withAppendedPath(
                        Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                        values.getAsString(FormsColumns.FORM_ID));
                getContext().getContentResolver().notifyChange(formUri, null);
                Uri idUri = Uri.withAppendedPath(
                        Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                        Long.toString(rowId));
                getContext().getContentResolver().notifyChange(idUri, null);

                return formUri;
            }
        } catch (Exception e) {
            log.w(t, "FAILED Insert into " + uri + " -- insert of row failed: " + e.toString());

            if (e instanceof SQLException) {
                throw (SQLException) e;
            } else {
                throw new SQLException(
                        "FAILED Insert into " + uri + " -- insert of row failed: " + e.toString());
            }
        }
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }

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

From source file:org.frc836.database.DBSyncService.java

private void processEvents(JSONArray events) {
    try {//  w w w.  ja v  a  2  s  .c o  m
        for (int i = 0; i < events.length(); i++) {
            JSONObject row = events.getJSONObject(i);
            Action action = Action.UPDATE;
            if (row.getInt(EVENT_LU_Entry.COLUMN_NAME_INVALID) != 0) {
                action = Action.DELETE;
            }
            ContentValues vals = new ContentValues();
            vals.put(EVENT_LU_Entry.COLUMN_NAME_ID, row.getInt(EVENT_LU_Entry.COLUMN_NAME_ID));
            vals.put(EVENT_LU_Entry.COLUMN_NAME_EVENT_NAME,
                    row.getString(EVENT_LU_Entry.COLUMN_NAME_EVENT_NAME));
            vals.put(EVENT_LU_Entry.COLUMN_NAME_EVENT_CODE,
                    row.getString(EVENT_LU_Entry.COLUMN_NAME_EVENT_CODE));
            vals.put(EVENT_LU_Entry.COLUMN_NAME_DATE_START,
                    row.getString(EVENT_LU_Entry.COLUMN_NAME_DATE_START));
            vals.put(EVENT_LU_Entry.COLUMN_NAME_TIMESTAMP,
                    DB.dateParser.format(new Date(row.getLong(EVENT_LU_Entry.COLUMN_NAME_TIMESTAMP) * 1000)));

            // check if this entry exists already
            String[] projection = { EVENT_LU_Entry.COLUMN_NAME_EVENT_NAME };
            String[] where = { vals.getAsString(EVENT_LU_Entry.COLUMN_NAME_ID) };
            synchronized (ScoutingDBHelper.lock) {

                SQLiteDatabase db = ScoutingDBHelper.getInstance().getWritableDatabase();

                Cursor c = db.query(EVENT_LU_Entry.TABLE_NAME, projection, // select
                        EVENT_LU_Entry.COLUMN_NAME_ID + "=?", where, null, // don't
                        // group
                        null, // don't filter
                        null, // don't order
                        "0,1"); // limit to 1
                try {
                    if (!c.moveToFirst()) {
                        if (action == Action.UPDATE)
                            action = Action.INSERT;
                        else if (action == Action.DELETE)
                            action = Action.NOTHING;
                    }

                    switch (action) {
                    case UPDATE:
                        db.update(EVENT_LU_Entry.TABLE_NAME, vals, EVENT_LU_Entry.COLUMN_NAME_ID + " = ?",
                                where);
                        break;
                    case INSERT:
                        db.insert(EVENT_LU_Entry.TABLE_NAME, null, vals);
                        break;
                    case DELETE:
                        db.delete(EVENT_LU_Entry.TABLE_NAME, EVENT_LU_Entry.COLUMN_NAME_ID + " = ?", where);
                        break;
                    default:
                    }
                } finally {
                    if (c != null)
                        c.close();
                    ScoutingDBHelper.getInstance().close();
                }
            }

        }
    } catch (JSONException e) {
        // TODO handle error
    }
}

From source file:org.frc836.database.DBSyncService.java

private void processRobots(JSONArray robots) {
    try {/*from www  .  ja  va  2s . c o m*/
        for (int i = 0; i < robots.length(); i++) {
            JSONObject row = robots.getJSONObject(i);
            Action action = Action.UPDATE;
            if (row.getInt(ROBOT_LU_Entry.COLUMN_NAME_INVALID) != 0) {
                action = Action.DELETE;
            }
            ContentValues vals = new ContentValues();
            vals.put(ROBOT_LU_Entry.COLUMN_NAME_ID, row.getInt(ROBOT_LU_Entry.COLUMN_NAME_ID));
            vals.put(ROBOT_LU_Entry.COLUMN_NAME_TEAM_ID, row.getString(ROBOT_LU_Entry.COLUMN_NAME_TEAM_ID));
            vals.put(ROBOT_LU_Entry.COLUMN_NAME_ROBOT_PHOTO,
                    row.getString(ROBOT_LU_Entry.COLUMN_NAME_ROBOT_PHOTO));
            vals.put(ROBOT_LU_Entry.COLUMN_NAME_TIMESTAMP,
                    DB.dateParser.format(new Date(row.getLong(ROBOT_LU_Entry.COLUMN_NAME_TIMESTAMP) * 1000)));

            // check if this entry exists already
            String[] projection = { ROBOT_LU_Entry.COLUMN_NAME_ID };
            String[] where = { vals.getAsString(ROBOT_LU_Entry.COLUMN_NAME_TEAM_ID) };
            synchronized (ScoutingDBHelper.lock) {

                SQLiteDatabase db = ScoutingDBHelper.getInstance().getWritableDatabase();

                Cursor c = db.query(ROBOT_LU_Entry.TABLE_NAME, projection, // select
                        ROBOT_LU_Entry.COLUMN_NAME_TEAM_ID + "=?", where, null, // don't
                        // group
                        null, // don't filter
                        null, // don't order
                        "0,1"); // limit to 1
                try {
                    if (!c.moveToFirst()) {
                        if (action == Action.UPDATE)
                            action = Action.INSERT;
                        else if (action == Action.DELETE)
                            action = Action.NOTHING;
                    }

                    switch (action) {
                    case UPDATE:
                        db.update(ROBOT_LU_Entry.TABLE_NAME, vals, ROBOT_LU_Entry.COLUMN_NAME_TEAM_ID + " = ?",
                                where);
                        break;
                    case INSERT:
                        db.insert(ROBOT_LU_Entry.TABLE_NAME, null, vals);
                        break;
                    case DELETE:
                        db.delete(ROBOT_LU_Entry.TABLE_NAME, ROBOT_LU_Entry.COLUMN_NAME_TEAM_ID + " = ?",
                                where);
                        break;
                    default:
                    }
                } finally {
                    if (c != null)
                        c.close();
                    ScoutingDBHelper.getInstance().close();
                }
            }
        }
    } catch (JSONException e) {
        // TODO handle error
    }
}

From source file:org.frc836.database.DBSyncService.java

private void processPositions(JSONArray positions) {
    try {/*from  w ww  .j  a  va  2 s  .c  o m*/
        for (int i = 0; i < positions.length(); i++) {
            JSONObject row = positions.getJSONObject(i);
            Action action = Action.UPDATE;
            if (row.getInt(POSITION_LU_Entry.COLUMN_NAME_INVALID) != 0) {
                action = Action.DELETE;
            }
            ContentValues vals = new ContentValues();
            vals.put(POSITION_LU_Entry.COLUMN_NAME_ID, row.getInt(POSITION_LU_Entry.COLUMN_NAME_ID));
            vals.put(POSITION_LU_Entry.COLUMN_NAME_POSITION,
                    row.getString(POSITION_LU_Entry.COLUMN_NAME_POSITION));
            vals.put(POSITION_LU_Entry.COLUMN_NAME_TIMESTAMP, DB.dateParser
                    .format(new Date(row.getLong(POSITION_LU_Entry.COLUMN_NAME_TIMESTAMP) * 1000)));

            // check if this entry exists already
            String[] projection = { POSITION_LU_Entry.COLUMN_NAME_POSITION };
            String[] where = { vals.getAsString(POSITION_LU_Entry.COLUMN_NAME_ID) };

            synchronized (ScoutingDBHelper.lock) {

                SQLiteDatabase db = ScoutingDBHelper.getInstance().getWritableDatabase();

                Cursor c = db.query(POSITION_LU_Entry.TABLE_NAME, projection, // select
                        POSITION_LU_Entry.COLUMN_NAME_ID + "=?", where, null, // don't
                        // group
                        null, // don't filter
                        null, // don't order
                        "0,1"); // limit to 1
                try {
                    if (!c.moveToFirst()) {
                        if (action == Action.UPDATE)
                            action = Action.INSERT;
                        else if (action == Action.DELETE)
                            action = Action.NOTHING;
                    }

                    switch (action) {
                    case UPDATE:
                        db.update(POSITION_LU_Entry.TABLE_NAME, vals, POSITION_LU_Entry.COLUMN_NAME_ID + " = ?",
                                where);
                        break;
                    case INSERT:
                        db.insert(POSITION_LU_Entry.TABLE_NAME, null, vals);
                        break;
                    case DELETE:
                        db.delete(POSITION_LU_Entry.TABLE_NAME, POSITION_LU_Entry.COLUMN_NAME_ID + " = ?",
                                where);
                        break;
                    default:
                    }
                } finally {
                    if (c != null)
                        c.close();
                    ScoutingDBHelper.getInstance().close();
                }
            }
        }
    } catch (JSONException e) {
        // TODO handle error
    }
}

From source file:me.piebridge.bible.Bible.java

public boolean saveHighlight(String osis, String verses) {
    if (highlighted.equals(verses)) {
        return false;
    }/*from ww  w.  java2 s  .c om*/
    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    if (!isDatabaseIntegrityOk(db)) {
        File path = mContext.getDatabasePath(AnnotationsDatabaseHelper.DATABASE_NAME);
        if (path != null && path.delete()) {
            return saveHighlight(osis, verses);
        }
        return false;
    }
    ContentValues values = new ContentValues();
    values.put(AnnotationsDatabaseHelper.COLUMN_OSIS, osis);
    values.put(AnnotationsDatabaseHelper.COLUMN_TYPE, "highlight");
    values.put(AnnotationsDatabaseHelper.COLUMN_VERSES, verses);
    if (highlightId == null) {
        highlightId = db.insert(AnnotationsDatabaseHelper.TABLE_ANNOTATIONS, null, values);
    } else {
        db.update(AnnotationsDatabaseHelper.TABLE_ANNOTATIONS, values,
                AnnotationsDatabaseHelper.COLUMN_ID + " = ?", new String[] { String.valueOf(highlightId) });
    }
    return true;
}

From source file:org.frc836.database.DBSyncService.java

private void processNotes(JSONArray notes) {
    try {//from   w  w w .  ja  va2  s .  c  o  m
        for (int i = 0; i < notes.length(); i++) {
            JSONObject row = notes.getJSONObject(i);
            Action action = Action.UPDATE;
            if (row.getInt(NOTES_OPTIONS_Entry.COLUMN_NAME_INVALID) != 0) {
                action = Action.DELETE;
            }
            ContentValues vals = new ContentValues();
            vals.put(NOTES_OPTIONS_Entry.COLUMN_NAME_ID, row.getInt(NOTES_OPTIONS_Entry.COLUMN_NAME_ID));
            vals.put(NOTES_OPTIONS_Entry.COLUMN_NAME_OPTION_TEXT,
                    row.getString(NOTES_OPTIONS_Entry.COLUMN_NAME_OPTION_TEXT));
            vals.put(NOTES_OPTIONS_Entry.COLUMN_NAME_TIMESTAMP, DB.dateParser
                    .format(new Date(row.getLong(NOTES_OPTIONS_Entry.COLUMN_NAME_TIMESTAMP) * 1000)));

            // check if this entry exists already
            String[] projection = { NOTES_OPTIONS_Entry.COLUMN_NAME_OPTION_TEXT };
            String[] where = { vals.getAsString(NOTES_OPTIONS_Entry.COLUMN_NAME_ID) };

            synchronized (ScoutingDBHelper.lock) {

                SQLiteDatabase db = ScoutingDBHelper.getInstance().getWritableDatabase();

                Cursor c = db.query(NOTES_OPTIONS_Entry.TABLE_NAME, projection, // select
                        NOTES_OPTIONS_Entry.COLUMN_NAME_ID + "=?", where, null, // don't
                        // group
                        null, // don't filter
                        null, // don't order
                        "0,1"); // limit to 1
                try {
                    if (!c.moveToFirst()) {
                        if (action == Action.UPDATE)
                            action = Action.INSERT;
                        else if (action == Action.DELETE)
                            action = Action.NOTHING;
                    }

                    switch (action) {
                    case UPDATE:
                        db.update(NOTES_OPTIONS_Entry.TABLE_NAME, vals,
                                NOTES_OPTIONS_Entry.COLUMN_NAME_ID + " = ?", where);
                        break;
                    case INSERT:
                        db.insert(NOTES_OPTIONS_Entry.TABLE_NAME, null, vals);
                        break;
                    case DELETE:
                        db.delete(NOTES_OPTIONS_Entry.TABLE_NAME, NOTES_OPTIONS_Entry.COLUMN_NAME_ID + " = ?",
                                where);
                        break;
                    default:
                    }
                } finally {
                    if (c != null)
                        c.close();
                    ScoutingDBHelper.getInstance().close();
                }
            }
        }
    } catch (JSONException e) {
        // TODO handle error
    }
}

From source file:org.frc836.database.DBSyncService.java

private void processWheelBase(JSONArray wheelBase) {
    try {// ww  w  .  ja  va 2s  .  c o m
        for (int i = 0; i < wheelBase.length(); i++) {
            JSONObject row = wheelBase.getJSONObject(i);
            Action action = Action.UPDATE;
            if (row.getInt(WHEEL_BASE_LU_Entry.COLUMN_NAME_INVALID) != 0) {
                action = Action.DELETE;
            }
            ContentValues vals = new ContentValues();
            vals.put(WHEEL_BASE_LU_Entry.COLUMN_NAME_ID, row.getInt(WHEEL_BASE_LU_Entry.COLUMN_NAME_ID));
            vals.put(WHEEL_BASE_LU_Entry.COLUMN_NAME_WHEEL_BASE_DESC,
                    row.getString(WHEEL_BASE_LU_Entry.COLUMN_NAME_WHEEL_BASE_DESC));
            vals.put(WHEEL_BASE_LU_Entry.COLUMN_NAME_TIMESTAMP, DB.dateParser
                    .format(new Date(row.getLong(WHEEL_BASE_LU_Entry.COLUMN_NAME_TIMESTAMP) * 1000)));

            // check if this entry exists already
            String[] projection = { WHEEL_BASE_LU_Entry.COLUMN_NAME_WHEEL_BASE_DESC };
            String[] where = { vals.getAsString(WHEEL_BASE_LU_Entry.COLUMN_NAME_ID) };

            synchronized (ScoutingDBHelper.lock) {

                SQLiteDatabase db = ScoutingDBHelper.getInstance().getWritableDatabase();

                Cursor c = db.query(WHEEL_BASE_LU_Entry.TABLE_NAME, projection, // select
                        WHEEL_BASE_LU_Entry.COLUMN_NAME_ID + "=?", where, null, // don't
                        // group
                        null, // don't filter
                        null, // don't order
                        "0,1"); // limit to 1
                try {
                    if (!c.moveToFirst()) {
                        if (action == Action.UPDATE)
                            action = Action.INSERT;
                        else if (action == Action.DELETE)
                            action = Action.NOTHING;
                    }

                    switch (action) {
                    case UPDATE:
                        db.update(WHEEL_BASE_LU_Entry.TABLE_NAME, vals,
                                WHEEL_BASE_LU_Entry.COLUMN_NAME_ID + " = ?", where);
                        break;
                    case INSERT:
                        db.insert(WHEEL_BASE_LU_Entry.TABLE_NAME, null, vals);
                        break;
                    case DELETE:
                        db.delete(WHEEL_BASE_LU_Entry.TABLE_NAME, WHEEL_BASE_LU_Entry.COLUMN_NAME_ID + " = ?",
                                where);
                        break;
                    default:
                    }
                } finally {
                    if (c != null)
                        c.close();
                    ScoutingDBHelper.getInstance().close();
                }
            }
        }
    } catch (JSONException e) {
        // TODO handle error
    }
}

From source file:org.frc836.database.DBSyncService.java

private void processWheelType(JSONArray wheelType) {
    try {//w  w w  .java 2s  . co  m
        for (int i = 0; i < wheelType.length(); i++) {
            JSONObject row = wheelType.getJSONObject(i);
            Action action = Action.UPDATE;
            if (row.getInt(WHEEL_TYPE_LU_Entry.COLUMN_NAME_INVALID) != 0) {
                action = Action.DELETE;
            }
            ContentValues vals = new ContentValues();
            vals.put(WHEEL_TYPE_LU_Entry.COLUMN_NAME_ID, row.getInt(WHEEL_TYPE_LU_Entry.COLUMN_NAME_ID));
            vals.put(WHEEL_TYPE_LU_Entry.COLUMN_NAME_WHEEL_TYPE_DESC,
                    row.getString(WHEEL_TYPE_LU_Entry.COLUMN_NAME_WHEEL_TYPE_DESC));
            vals.put(WHEEL_TYPE_LU_Entry.COLUMN_NAME_TIMESTAMP, DB.dateParser
                    .format(new Date(row.getLong(WHEEL_TYPE_LU_Entry.COLUMN_NAME_TIMESTAMP) * 1000)));

            // check if this entry exists already
            String[] projection = { WHEEL_TYPE_LU_Entry.COLUMN_NAME_WHEEL_TYPE_DESC };
            String[] where = { vals.getAsString(WHEEL_TYPE_LU_Entry.COLUMN_NAME_ID) };

            synchronized (ScoutingDBHelper.lock) {

                SQLiteDatabase db = ScoutingDBHelper.getInstance().getWritableDatabase();

                Cursor c = db.query(WHEEL_TYPE_LU_Entry.TABLE_NAME, projection, // select
                        WHEEL_TYPE_LU_Entry.COLUMN_NAME_ID + "=?", where, null, // don't
                        // group
                        null, // don't filter
                        null, // don't order
                        "0,1"); // limit to 1
                try {
                    if (!c.moveToFirst()) {
                        if (action == Action.UPDATE)
                            action = Action.INSERT;
                        else if (action == Action.DELETE)
                            action = Action.NOTHING;
                    }

                    switch (action) {
                    case UPDATE:
                        db.update(WHEEL_TYPE_LU_Entry.TABLE_NAME, vals,
                                WHEEL_TYPE_LU_Entry.COLUMN_NAME_ID + " = ?", where);
                        break;
                    case INSERT:
                        db.insert(WHEEL_TYPE_LU_Entry.TABLE_NAME, null, vals);
                        break;
                    case DELETE:
                        db.delete(WHEEL_TYPE_LU_Entry.TABLE_NAME, WHEEL_TYPE_LU_Entry.COLUMN_NAME_ID + " = ?",
                                where);
                        break;
                    default:
                    }
                } finally {
                    if (c != null)
                        c.close();
                    ScoutingDBHelper.getInstance().close();
                }
            }
        }
    } catch (JSONException e) {
        // TODO handle error
    }
}

From source file:org.frc836.database.DBSyncService.java

private void processConfig(JSONArray config) {
    try {/*from   ww  w  .j a  va 2  s.c  o  m*/
        for (int i = 0; i < config.length(); i++) {
            JSONObject row = config.getJSONObject(i);
            Action action = Action.UPDATE;
            if (row.getInt(CONFIGURATION_LU_Entry.COLUMN_NAME_INVALID) != 0) {
                action = Action.DELETE;
            }
            ContentValues vals = new ContentValues();
            vals.put(CONFIGURATION_LU_Entry.COLUMN_NAME_ID, row.getInt(CONFIGURATION_LU_Entry.COLUMN_NAME_ID));
            vals.put(CONFIGURATION_LU_Entry.COLUMN_NAME_CONFIGURATION_DESC,
                    row.getString(CONFIGURATION_LU_Entry.COLUMN_NAME_CONFIGURATION_DESC));
            vals.put(CONFIGURATION_LU_Entry.COLUMN_NAME_TIMESTAMP, DB.dateParser
                    .format(new Date(row.getLong(CONFIGURATION_LU_Entry.COLUMN_NAME_TIMESTAMP) * 1000)));

            // check if this entry exists already
            String[] projection = { CONFIGURATION_LU_Entry.COLUMN_NAME_CONFIGURATION_DESC };
            String[] where = { vals.getAsString(CONFIGURATION_LU_Entry.COLUMN_NAME_ID) };
            synchronized (ScoutingDBHelper.lock) {

                SQLiteDatabase db = ScoutingDBHelper.getInstance().getWritableDatabase();

                Cursor c = db.query(CONFIGURATION_LU_Entry.TABLE_NAME, projection, // select
                        CONFIGURATION_LU_Entry.COLUMN_NAME_ID + "=?", where, null, // don't
                        // group
                        null, // don't filter
                        null, // don't order
                        "0,1"); // limit to 1
                try {
                    if (!c.moveToFirst()) {
                        if (action == Action.UPDATE)
                            action = Action.INSERT;
                        else if (action == Action.DELETE)
                            action = Action.NOTHING;
                    }

                    switch (action) {
                    case UPDATE:
                        db.update(CONFIGURATION_LU_Entry.TABLE_NAME, vals,
                                CONFIGURATION_LU_Entry.COLUMN_NAME_ID + " = ?", where);
                        break;
                    case INSERT:
                        db.insert(CONFIGURATION_LU_Entry.TABLE_NAME, null, vals);
                        break;
                    case DELETE:
                        db.delete(CONFIGURATION_LU_Entry.TABLE_NAME,
                                CONFIGURATION_LU_Entry.COLUMN_NAME_ID + " = ?", where);
                        break;
                    default:
                    }
                } finally {
                    if (c != null)
                        c.close();
                    ScoutingDBHelper.getInstance().close();
                }
            }
        }
    } catch (JSONException e) {
        // TODO handle error
    }
}

From source file:org.jsharkey.oilcan.ScriptDatabase.java

/**
 * Import the given script into our database.
 * @throws Exception if problem parsing script 
 *//*from   w ww  .  j  a va2s . c  o  m*/
public long insertScript(SQLiteDatabase db, String raw) throws Exception {
    if (db == null)
        db = this.getWritableDatabase();

    // extract metadata from script comments
    String name = UNKNOWN, author = UNKNOWN, descrip = UNKNOWN;
    StringBuilder include = new StringBuilder();
    include.append('(');

    try {
        Matcher matcher = headerRegex.matcher(raw);
        while (matcher.find()) {
            String key = matcher.group(1), value = matcher.group(2);

            Log.d(TAG, String.format("found header %s=%s", key, value));

            if ("name".equals(key)) {
                name = value;
            } else if ("author".equals(key)) {
                author = value;
            } else if ("description".equals(key)) {
                descrip = value;
            } else if ("include".equals(key)) {
                include.append(formatDomain(value));
                include.append('|');
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "Problem while parsing script header", e);
    }

    String domainregex = "";
    if (include.length() > 0) {
        // replace last '|' with a closing bracket
        include.setCharAt(include.length() - 1, ')');
        domainregex = include.toString();
    }

    // script is valid if has name and parsable domain regex
    if (UNKNOWN.equals(name))
        throw new Exception("No name found in script");

    try {
        Pattern.compile(domainregex);
    } catch (Exception e) {
        throw new Exception("Problem parsing domain regex", e);
    }

    //Log.d(TAG, String.format("domainregex=%s", domainregex));

    ContentValues values = new ContentValues();
    values.put(FIELD_SCRIPT_NAME, name);
    values.put(FIELD_SCRIPT_AUTHOR, author);
    values.put(FIELD_SCRIPT_DESCRIP, descrip);
    values.put(FIELD_SCRIPT_DOMAINREGEX, domainregex);
    values.put(FIELD_SCRIPT_CONTENT, raw);
    values.put(FIELD_SCRIPT_ENABLED, 1);

    return db.insert(TABLE_SCRIPTS, null, values);

}