Example usage for android.database.sqlite SQLiteStatement executeInsert

List of usage examples for android.database.sqlite SQLiteStatement executeInsert

Introduction

In this page you can find the example usage for android.database.sqlite SQLiteStatement executeInsert.

Prototype

public long executeInsert() 

Source Link

Document

Execute this SQL statement and return the ID of the row inserted due to this call.

Usage

From source file:fr.openbike.android.database.OpenBikeDBAdapter.java

public void insertStations(JSONArray jsonArray) throws JSONException, SQLiteException {

    InsertHelper stationsInsertHelper = new InsertHelper(mDb, STATIONS_TABLE);
    InsertHelper virtualInsertHelper = new InsertHelper(mDb, STATIONS_VIRTUAL_TABLE);

    final int idColumn = stationsInsertHelper.getColumnIndex(BaseColumns._ID);
    final int nameColumn = stationsInsertHelper.getColumnIndex(KEY_NAME);
    final int openColumn = stationsInsertHelper.getColumnIndex(KEY_OPEN);
    final int bikesColumn = stationsInsertHelper.getColumnIndex(KEY_BIKES);
    final int slotsColumn = stationsInsertHelper.getColumnIndex(KEY_SLOTS);
    final int addressColumn = stationsInsertHelper.getColumnIndex(KEY_ADDRESS);
    final int latitudeColumn = stationsInsertHelper.getColumnIndex(KEY_LATITUDE);
    final int longitudeColumn = stationsInsertHelper.getColumnIndex(KEY_LONGITUDE);
    final int paymentColumn = stationsInsertHelper.getColumnIndex(KEY_PAYMENT);
    final int specialColumn = stationsInsertHelper.getColumnIndex(KEY_SPECIAL);
    final int networkColumn = stationsInsertHelper.getColumnIndex(KEY_NETWORK);
    final int favoriteColumn = stationsInsertHelper.getColumnIndex(KEY_FAVORITE);

    final int virtualIdColumn = virtualInsertHelper.getColumnIndex(BaseColumns._ID);
    final int virtualNameColumn = virtualInsertHelper.getColumnIndex(KEY_NAME);
    final int virtualNetworkColumn = virtualInsertHelper.getColumnIndex(KEY_NETWORK);

    final int networkId = jsonArray.getJSONObject(0).getInt(Station.NETWORK);
    final int size = jsonArray.length();

    final String sql = "INSERT INTO " + STATIONS_TABLE + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?);";

    final String sql_virtual = "INSERT INTO " + STATIONS_VIRTUAL_TABLE + " VALUES (?,?,?);";
    virtualInsertHelper.close();/*from   w w w.  ja  va 2 s.  com*/
    stationsInsertHelper.close();
    try {
        mDb.beginTransaction();
        SQLiteStatement insert = mDb.compileStatement(sql);
        SQLiteStatement insert_virtual = mDb.compileStatement(sql_virtual);
        int id;
        String name;
        for (int i = 0; i < size; i++) {
            JSONObject jsonStation = jsonArray.getJSONObject(i);
            id = jsonStation.getInt(Station.ID);
            name = jsonStation.getString(Station.NAME);
            insert.bindLong(idColumn, id);
            insert.bindString(nameColumn, name);
            insert.bindLong(openColumn, jsonStation.getBoolean(Station.OPEN) ? 1 : 0);
            insert.bindLong(bikesColumn, jsonStation.getInt(Station.BIKES));
            insert.bindLong(slotsColumn, jsonStation.getInt(Station.SLOTS));
            insert.bindString(addressColumn, jsonStation.getString(Station.ADDRESS));
            insert.bindLong(latitudeColumn, (int) (jsonStation.getDouble(Station.LATITUDE) * 1E6));
            insert.bindLong(longitudeColumn, (int) (jsonStation.getDouble(Station.LONGITUDE) * 1E6));
            insert.bindLong(paymentColumn, jsonStation.getBoolean(Station.PAYMENT) ? 1 : 0);
            insert.bindLong(specialColumn, jsonStation.getBoolean(Station.SPECIAL) ? 1 : 0);
            insert.bindLong(networkColumn, networkId);
            insert.bindLong(favoriteColumn, 0); // Favorite
            insert.executeInsert();

            insert_virtual.bindLong(virtualNetworkColumn, networkId);
            insert_virtual.bindLong(virtualIdColumn, id);
            insert_virtual.bindString(virtualNameColumn, name);
            insert_virtual.executeInsert();
        }
        mDb.setTransactionSuccessful();
    } catch (JSONException e) {
        throw e;
    } catch (SQLException e) {
        throw e;
    } finally {
        mDb.endTransaction();
    }
}

From source file:de.stadtrallye.rallyesoft.model.chat.Chatroom.java

/**
 * Save ChatEntries to DB/*from w ww  .jav a2  s .  com*/
 *
 * @param entries All entries that have a higher chatID than this.newestID will be saved to DB
 */
private void saveChats(List<ChatEntry> entries) {
    //KEY_ID, KEY_TIME, FOREIGN_GROUP, FOREIGN_USER, KEY_MESSAGE, KEY_PICTURE, FOREIGN_ROOM
    SQLiteStatement s = getDb().compileStatement("INSERT INTO " + DatabaseHelper.Chats.TABLE + " ("
            + DatabaseHelper.strStr(DatabaseHelper.Chats.COLS) + ") VALUES (?, ?, ?, ?, ?, ?, " + chatroomID
            + ")");

    int chatId;
    List<ChatEntry> update = new ArrayList<>();

    stateLock.writeLock().lock();
    try {
        ChatEntry c;
        for (Iterator<ChatEntry> i = entries.iterator(); i.hasNext();) {
            c = i.next();

            if (c.chatID <= newestID) { // Already seen this entry
                if (c.timestamp > lastUpdateTime) { // Entry has changed since last seen
                    update.add(c);
                }
                i.remove(); // ignore
                continue;

            }

            try {
                //            Log.d(THIS, "Inserted "+c+" in Messages");

                s.bindLong(1, c.chatID);
                s.bindLong(2, c.timestamp);
                s.bindLong(3, c.groupID);
                s.bindLong(4, c.userID);
                s.bindString(5, c.message);

                if (c.pictureHash != null)
                    s.bindString(6, c.pictureHash);
                else
                    s.bindNull(6);

                chatId = (int) s.executeInsert();

                //            Log.d(THIS, "Inserted "+c+" in Chats");

                if (chatId != c.chatID)
                    throw new SQLDataException();

            } catch (Exception e) {
                Log.e(THIS, "Single Insert failed", e);
            }
        }

        if (entries.size() > 0) {
            ChatEntry last = entries.get(entries.size() - 1);

            setLast(last.timestamp, last.chatID);
        }

        Log.i(THIS, "Received " + entries.size() + " new Chats in Chatroom " + chatroomID + " since "
                + lastUpdateTime);

    } catch (Exception e) {
        Log.e(THIS, "All Inserts failed", e);
    } finally {
        stateLock.writeLock().unlock();
        s.close();
    }

    if (update.size() > 0) {
        Log.w(THIS, "Chat entries were changed on Server: " + update);
        for (ChatEntry c : update) {
            editChat(c);
        }
    }

    checkForNewUsers();
    checkForNewGroups();

    notifyChatsChanged();
}

From source file:com.ichi2.anki.SyncClient.java

private void deleteMedia(JSONArray ids) {
    Log.i(AnkiDroidApp.TAG, "deleteMedia");
    AnkiDb ankiDB = AnkiDatabaseManager.getDatabase(mDeck.getDeckPath());

    String idsString = Utils.ids2str(ids);

    // Get filenames
    ArrayList<String> files = ankiDB.queryColumn(String.class,
            "SELECT filename FROM media WHERE id IN " + idsString, 0);

    // Note the media to delete (Insert the media to delete into mediaDeleted)
    double now = Utils.now();
    String sqlInsert = "INSERT INTO mediaDeleted SELECT id, " + String.format(Utils.ENGLISH_LOCALE, "%f", now)
            + " FROM media WHERE media.id = ?";
    SQLiteStatement statement = ankiDB.getDatabase().compileStatement(sqlInsert);
    int len = ids.length();
    for (int i = 0; i < len; i++) {
        try {/*from ww w  . ja v  a  2 s. co m*/
            Log.i(AnkiDroidApp.TAG, "Inserting media " + ids.getLong(i) + " into mediaDeleted");
            statement.bindLong(1, ids.getLong(i));
            statement.executeInsert();
        } catch (JSONException e) {
            Log.i(AnkiDroidApp.TAG, "JSONException = " + e.getMessage());
        }
    }
    statement.close();

    // Delete media
    Log.i(AnkiDroidApp.TAG, "Deleting media in = " + idsString);
    ankiDB.getDatabase().execSQL("DELETE FROM media WHERE id IN " + idsString);
}

From source file:io.requery.android.database.sqlite.SQLiteDatabase.java

/**
 * General method for inserting a row into the database.
 *
 * @param table the table to insert the row into
 * @param nullColumnHack optional; may be <code>null</code>.
 *            SQL doesn't allow inserting a completely empty row without
 *            naming at least one column name.  If your provided <code>initialValues</code> is
 *            empty, no column names are known and an empty row can't be inserted.
 *            If not set to null, the <code>nullColumnHack</code> parameter
 *            provides the name of nullable column name to explicitly insert a NULL into
 *            in the case where your <code>initialValues</code> is empty.
 * @param initialValues this map contains the initial column values for the
 *            row. The keys should be the column names and the values the
 *            column values//  w  ww. ja v a  2 s  . co m
 * @param conflictAlgorithm for insert conflict resolver
 * @return the row ID of the newly inserted row
 * OR the primary key of the existing row if the input param 'conflictAlgorithm' =
 * {@link #CONFLICT_IGNORE}
 * OR -1 if any error
 */
@SuppressWarnings("StringConcatenationInsideStringBufferAppend")
public long insertWithOnConflict(String table, String nullColumnHack, ContentValues initialValues,
        @ConflictAlgorithm int conflictAlgorithm) {
    acquireReference();
    try {
        StringBuilder sql = new StringBuilder();
        sql.append("INSERT");
        sql.append(CONFLICT_VALUES[conflictAlgorithm]);
        sql.append(" INTO ");
        sql.append(table);
        sql.append('(');

        Object[] bindArgs = null;
        int size = (initialValues != null && initialValues.size() > 0) ? initialValues.size() : 0;
        if (size > 0) {
            bindArgs = new Object[size];
            int i = 0;
            for (Map.Entry<String, Object> entry : initialValues.valueSet()) {
                sql.append((i > 0) ? "," : "");
                sql.append(entry.getKey());
                bindArgs[i++] = entry.getValue();
            }
            sql.append(')');
            sql.append(" VALUES (");
            for (i = 0; i < size; i++) {
                sql.append((i > 0) ? ",?" : "?");
            }
        } else {
            sql.append(nullColumnHack + ") VALUES (NULL");
        }
        sql.append(')');

        SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs);
        try {
            return statement.executeInsert();
        } finally {
            statement.close();
        }
    } finally {
        releaseReference();
    }
}

From source file:com.gimranov.zandy.app.task.APIRequest.java

/**
 * Saves the APIRequest's basic info to the database. Does not maintain handler information.
 * @param db// w  w w  . j  av  a2 s  .c  o m
 */
public void save(Database db) {
    try {
        Log.d(TAG, "Saving APIRequest to database: " + uuid + " " + query);
        SQLiteStatement insert = db.compileStatement("insert or replace into apirequests "
                + "(uuid, type, query, key, method, disposition, if_match, update_key, update_type, "
                + "created, last_attempt, status, body)" + " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)");
        // Why, oh why does bind* use 1-based indexing? And cur.get* uses 0-based!
        insert.bindString(1, uuid);
        insert.bindLong(2, (long) type);

        String createdUnix = Long.toString(created.getTime());
        String lastAttemptUnix;
        if (lastAttempt == null)
            lastAttemptUnix = null;
        else
            lastAttemptUnix = Long.toString(lastAttempt.getTime());
        String status = Integer.toString(this.status);

        // Iterate through null-allowed strings and bind them
        String[] strings = { query, key, method, disposition, ifMatch, updateKey, updateType, createdUnix,
                lastAttemptUnix, status, body };
        for (int i = 0; i < strings.length; i++) {
            Log.d(TAG, (3 + i) + ":" + strings[i]);
            if (strings[i] == null)
                insert.bindNull(3 + i);
            else
                insert.bindString(3 + i, strings[i]);
        }

        insert.executeInsert();
        insert.clearBindings();
        insert.close();
    } catch (SQLiteException e) {
        Log.e(TAG, "Exception compiling or running insert statement", e);
        throw e;
    }
}