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.almarsoft.GroundhogReader.lib.DBUtils.java

public static void logSentMessage(String msgId, String group, Context context) {
    int groupid = getGroupIdFromName(group, context);

    DBHelper db = new DBHelper(context);
    SQLiteDatabase dbwrite = db.getWritableDatabase();

    /* Check first that the number of logged messages for this group is not greater than the 
    * limit impossed per group, because if it's greater we must delete number-limit older logs
    * until the table only has the limit. This is done this way because on the MessageList a set
    * is built with the post messages from that group, and then every loaded message's msgId is checked 
    * to see if it's in the set (to check for replies to our messages), so allowing it to grow too much
    * could make the MessageView slow//from  www .  java 2  s .  c o  m
    */

    Cursor c = dbwrite.rawQuery(
            "SELECT _id FROM sent_posts_log WHERE subscribed_group_id=" + groupid + " ORDER BY _id", null);
    int count = c.getCount();
    int toKill = count - UsenetConstants.SENT_POSTS_LOG_LIMIT_PER_GROUP;
    int kennyId;

    if (toKill > 0) {
        // Delete some more than needed so we don't have to do this on every post sent
        toKill += UsenetConstants.SENT_POST_KILL_ADITIONAL;
        c.moveToFirst();

        for (int i = 0; i < toKill; i++) {
            kennyId = c.getInt(0);
            dbwrite.execSQL("DELETE FROM sent_posts_log WHERE _id=" + kennyId);
            c.moveToNext();
        }
    }
    c.close();

    // Now we have room for sure, insert the log
    ContentValues cv = new ContentValues(2);
    cv.put("server_article_id", msgId);
    cv.put("subscribed_group_id", groupid);
    dbwrite.insert("sent_posts_log", null, cv);

    dbwrite.close();
    db.close();
}

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

public long addMessage(String chatId, String buddyId, String type, String content, String url, String status,
        long othersId) {
    //Log.d("DATABASE", "Adding a message");
    SQLiteDatabase db = mDbHelper.getWritableDatabase();
    //remove everything after @ if it exists
    int index = buddyId.indexOf('@');
    if (index >= 0) {
        buddyId = buddyId.substring(0, index);
    }/* www .jav a  2 s . co m*/
    index = chatId.indexOf('@');
    if (index >= 0) {
        chatId = chatId.substring(0, index);
    }

    ContentValues values = new ContentValues();
    values.put(MessageHistoryContract.MessageEntry.COLUMN_NAME_BUDDY_ID, buddyId);
    values.put(MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TYPE, type);
    values.put(MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_CONTENT, content);
    values.put(MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_URL, url);
    values.put(MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_STATUS, status);
    values.put(MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TIMESTAMP, new Date().getTime());
    values.put(MessageHistoryContract.MessageEntry.COLUMN_NAME_OTHERS_ID, othersId);
    long result = db.insert(chatId, MessageHistoryContract.MessageEntry._ID, values);
    db.close();
    return result;
}

From source file:org.ohmage.db.DbHelper.java

/**
 * Adds a response to the feedback database.
 * //from   w  w w  . j a v  a  2  s . com
 * @return the ID of the inserted record, or -1 if unsuccessful
 */
public long addResponseRow(SQLiteDatabase db, ContentValues values) {
    long rowId = -1;

    // extract data that we'll need to parse the json + insert prompt
    // responses
    String response = values.getAsString(Responses.RESPONSE_JSON);
    String campaignUrn = values.getAsString(Responses.CAMPAIGN_URN);
    String surveyId = values.getAsString(Responses.SURVEY_ID);

    try {
        // start a transaction involving the following operations:
        // 1) insert feedback response row
        // 2) parse json-encoded responses and insert one row into prompts
        // per entry
        db.beginTransaction();

        // do the actual insert into feedback responses
        rowId = db.insert(Tables.RESPONSES, null, values);

        // check if it succeeded; if not, we can't do anything
        if (rowId == -1)
            return -1;

        if (populatePromptsFromResponseJSON(db, rowId, response, campaignUrn, surveyId)) {
            // and we're done; finalize the transaction
            db.setTransactionSuccessful();
        }
        // else we fail and the transaction gets rolled back
    } catch (SQLiteConstraintException e) {
        Log.e(TAG, "Attempted to insert record that violated a SQL constraint (likely the hashcode)");
        return -1;
    } catch (Exception e) {
        Log.e(TAG, "Generic exception thrown from db insert", e);
        return -1;
    } finally {
        db.endTransaction();
        // db.close();
    }

    return rowId;
}

From source file:com.osfans.trime.DictionaryHelper.java

private boolean importDict(InputStream is) {
    boolean success = false;
    SQLiteDatabase db = getWritableDatabase();
    db.beginTransaction();//from  www .  j  a v a 2  s  . c  o  m
    try {
        String line;
        StringBuilder content = new StringBuilder();
        InputStreamReader ir = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(ir);
        while ((line = br.readLine()) != null && !line.contentEquals(fs)) {
            content.append(line);
            content.append(newline);
        }

        Yaml yaml = new Yaml();
        Map<String, Object> y = (Map<String, Object>) (yaml.load(content.toString()));
        String table = (String) y.get("name");

        db.execSQL("DROP TABLE IF EXISTS " + table);
        db.execSQL(String.format("CREATE VIRTUAL TABLE %s USING fts3(hz, py)", table));

        ContentValues initialValues = new ContentValues(2);
        int max = is.available();
        int progress = 0;
        int count = 0;
        while ((line = br.readLine()) != null) {
            if (line.startsWith(comment))
                continue;
            String[] s = line.split("\t");
            if (s.length < 2)
                continue;
            initialValues.put("hz", s[0]);
            initialValues.put("py", s[1]);
            db.insert(table, null, initialValues);
            initialValues.clear();
            count++;
            if ((count % 1000) == 0) {
                progress = max - is.available();
                mBuilder.setProgress(max, progress, false)
                        .setContentText(String.format("%d / 100", progress * 100 / max));
                mNotifyManager.notify(notify_id, mBuilder.build());
            }
        }
        is.close();
        db.setTransactionSuccessful();
        success = true;
    } catch (Exception e) {
        throw new RuntimeException("Error import dict", e);
    } finally {
        db.endTransaction();
        mNotifyManager.cancel(notify_id);
    }
    return success;
}

From source file:com.google.samples.apps.topeka.persistence.TopekaDatabaseHelper.java

private void fillQuizzesForCategory(SQLiteDatabase db, ContentValues values, JSONArray quizzes,
        String categoryId) throws JSONException {
    JSONObject quiz;/*from  w ww  . ja  va2  s . c o m*/
    for (int i = 0; i < quizzes.length(); i++) {
        quiz = quizzes.getJSONObject(i);
        values.clear();
        values.put(QuizTable.FK_CATEGORY, categoryId);
        values.put(QuizTable.COLUMN_TYPE, quiz.getString(JsonAttributes.TYPE));
        values.put(QuizTable.COLUMN_QUESTION, quiz.getString(JsonAttributes.QUESTION));
        values.put(QuizTable.COLUMN_ANSWER, quiz.getString(JsonAttributes.ANSWER));
        putNonEmptyString(values, quiz, JsonAttributes.OPTIONS, QuizTable.COLUMN_OPTIONS);
        putNonEmptyString(values, quiz, JsonAttributes.MIN, QuizTable.COLUMN_MIN);
        putNonEmptyString(values, quiz, JsonAttributes.MAX, QuizTable.COLUMN_MAX);
        putNonEmptyString(values, quiz, JsonAttributes.START, QuizTable.COLUMN_START);
        putNonEmptyString(values, quiz, JsonAttributes.END, QuizTable.COLUMN_END);
        putNonEmptyString(values, quiz, JsonAttributes.STEP, QuizTable.COLUMN_STEP);
        db.insert(QuizTable.NAME, null, values);
    }
}

From source file:it.bradipao.berengar.DbTool.java

public static int json2table(SQLiteDatabase mDB, JSONObject jsonTable) {

    // vars/*  w w w  .  ja va 2 s . c  o m*/
    JSONArray jsonRows = new JSONArray();
    JSONArray jsonColsName = new JSONArray();
    JSONArray jsonCols = null;
    ContentValues cv = null;

    int iRes = 0;
    try {
        // init database transaction
        mDB.beginTransaction();
        // fetch table name and drop if exists
        String sTableName = jsonTable.getString("table_name");
        mDB.execSQL("DROP TABLE IF EXISTS " + sTableName);
        if (GOLOG)
            Log.d(LOGTAG, "TABLE NAME : " + sTableName);
        // fetch and execute create sql
        String sTableSql = jsonTable.getString("table_sql");
        mDB.execSQL(sTableSql);
        // fetch columns name
        jsonColsName = jsonTable.getJSONArray("cols_name");
        // fetch rows array
        jsonRows = jsonTable.getJSONArray("rows");
        // iterate through rows
        for (int i = 0; i < jsonRows.length(); i++) {
            // fetch columns
            jsonCols = jsonRows.getJSONArray(i);
            // perform insert
            cv = new ContentValues();
            for (int j = 0; j < jsonCols.length(); j++)
                cv.put(jsonColsName.getString(j), jsonCols.getString(j));
            mDB.insert(sTableName, null, cv);
            if (GOLOG)
                Log.d(LOGTAG, "INSERT IN " + sTableName + " ID=" + jsonCols.getString(0));
        }
        iRes++;
        // set transaction successful
        mDB.setTransactionSuccessful();
    } catch (Exception e) {
        Log.e(LOGTAG, "error in json2table", e);
    } finally {
        // end transaction, commit if successful else rollback
        mDB.endTransaction();
    }

    return iRes;
}

From source file:org.akop.crosswords.Storage.java

public long write(long folderId, long puzzleId, Crossword crossword) {
    long started = SystemClock.uptimeMillis();

    StorageHelper helper = getHelper();/* w ww .  j  a  va  2s. c  om*/
    SQLiteDatabase db = helper.getWritableDatabase();
    ContentValues cv;

    try {
        cv = new ContentValues();
        cv.put(Puzzle.CLASS, crossword.getClass().getName());
        cv.put(Puzzle.SOURCE_URL, crossword.getSourceUrl());
        cv.put(Puzzle.TITLE, crossword.getTitle());
        cv.put(Puzzle.AUTHOR, crossword.getAuthor());
        cv.put(Puzzle.COPYRIGHT, crossword.getCopyright());
        cv.put(Puzzle.HASH, crossword.getHash());
        cv.put(Puzzle.SOURCE_ID, crossword.getSourceId());
        cv.put(Puzzle.FOLDER_ID, folderId);
        cv.put(Puzzle.OBJECT, mGson.toJson(crossword));
        cv.put(Puzzle.OBJECT_VERSION, 1);
        cv.put(Puzzle.LAST_UPDATED, System.currentTimeMillis());

        Long millis = null;
        if (crossword.getDate() != null) {
            millis = crossword.getDate().getMillis();
        }
        cv.put(Puzzle.DATE, millis);

        if (puzzleId != ID_NOT_FOUND) {
            db.update(Puzzle.TABLE, cv, Puzzle._ID + " = " + puzzleId, null);
        } else {
            puzzleId = db.insert(Puzzle.TABLE, null, cv);
        }
    } finally {
        db.close();
    }

    Crosswords.logv("Wrote crossword %s (%dms)", crossword.getHash(), SystemClock.uptimeMillis() - started);

    Intent outgoing = new Intent(ACTION_PUZZLE_CHANGE);
    outgoing.putExtra(INTENT_PUZZLE_ID, puzzleId);
    outgoing.putExtra(INTENT_PUZZLE_URL, crossword.getSourceUrl());

    sendLocalBroadcast(outgoing);

    return puzzleId;
}

From source file:com.odoo.core.orm.OModel.java

public void storeManyToManyRecord(String column_name, int row_id, List<Integer> relationIds, Command command)
        throws InvalidObjectException {
    OColumn column = getColumn(column_name);
    if (column != null) {
        OModel rel_model = createInstance(column.getType());
        String table = getTableName() + "_" + rel_model.getTableName() + "_rel";
        String base_column = getTableName() + "_id";
        String rel_column = rel_model.getTableName() + "_id";

        SQLiteDatabase db = getWritableDatabase();
        try {// w w  w. j  a va  2  s  .  c o  m
            switch (command) {
            case Add:
                if (relationIds.size() > 0) {
                    for (int id : relationIds) {
                        ContentValues values = new ContentValues();
                        values.put(base_column, row_id);
                        values.put(rel_column, id);
                        values.put("_write_date", ODateUtils.getDate());
                        db.insert(table, null, values);
                    }
                }
                break;
            case Update:
                break;
            case Delete:
                // Deleting records to relation model
                if (relationIds.size() > 0) {
                    for (int id : relationIds) {
                        db.delete(table, base_column + " = ? AND  " + rel_column + " = ?",
                                new String[] { row_id + "", id + "" });
                    }
                }
                break;
            case Replace:
                // Removing old entries
                db.delete(table, base_column + " = ?", new String[] { row_id + "" });
                // Creating new entries
                storeManyToManyRecord(column_name, row_id, relationIds, Command.Add);
                break;
            }
        } finally {
            db.close();
            rel_model.close();
        }
    } else {
        throw new InvalidObjectException(
                "Column [" + column_name + "] not found in " + getModelName() + " model.");

    }
}

From source file:org.totschnig.myexpenses.provider.TransactionDatabase.java

private void insertDefaultAccount(SQLiteDatabase db) {
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_LABEL, mCtx.getString(R.string.default_account_name));
    initialValues.put(KEY_OPENING_BALANCE, 0);
    initialValues.put(KEY_DESCRIPTION, mCtx.getString(R.string.default_account_description));
    Currency localCurrency = Utils.getLocalCurrency();
    initialValues.put(KEY_CURRENCY, localCurrency.getCurrencyCode());
    initialValues.put(KEY_TYPE, AccountType.CASH.name());
    initialValues.put(KEY_GROUPING, Grouping.NONE.name());
    initialValues.put(KEY_COLOR, Account.DEFAULT_COLOR);
    db.insert(TABLE_ACCOUNTS, null, initialValues);
    Money.ensureFractionDigitsAreCached(localCurrency);
}

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

private void insertOrUpdate(String table, String nullColumnHack, ContentValues values, String idColumnName,
        String whereClause, String[] whereArgs) {
    synchronized (ScoutingDBHelper.lock) {
        SQLiteDatabase db = ScoutingDBHelper.getInstance().getWritableDatabase();

        String[] projection = { idColumnName };

        Cursor c = db.query(table, projection, whereClause, whereArgs, null, null, null, "0,1");
        try {/*from  ww w.  j  a  v  a2s  .  c  o  m*/
            if (c.moveToFirst()) {
                String[] id = { c.getString(c.getColumnIndexOrThrow(idColumnName)) };
                values.put(COLUMN_NAME_TIMESTAMP, dateParser.format(new Date()));
                db.update(table, values, idColumnName + "=?", id);
            } else {
                db.insert(table, nullColumnHack, values);
            }
        } finally {
            if (c != null)
                c.close();
            ScoutingDBHelper.getInstance().close();
        }
    }
}