Example usage for android.database.sqlite SQLiteStatement clearBindings

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

Introduction

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

Prototype

public void clearBindings() 

Source Link

Document

Clears all existing bindings.

Usage

From source file:com.aquatest.dbinterface.tools.DatabaseUpdater.java

/**
 * Populates the "?" parameters in the prepared statement with values from
 * the included JSON object. It is assumed that the prepared statement was
 * created based on the same set of field names (in the same order) as have
 * been passed to this method.//from w w w  .jav a  2  s . c o  m
 * 
 * @param preparedStatement
 *            previously prepared SQL statement, which includes "?"
 *            parameter placeholders
 * @param type
 *            Operation type. Can be one of <code>TYPE_ADDED</code>,
 *            <code>TYPE_UPDATED</code> or <code>TYPE_DELETED</code>
 * @param fieldNames
 *            array of field names relating to this query
 * @param dataRow
 *            JSON object containing data relevant to this prepared
 *            statement
 * @throws JSONException
 *             if the JSON array or data row contain invalid JSON
 */
// method declared static for Android optimisation
private static void bindQueryParameters(SQLiteStatement preparedStatement, int type, JSONArray fieldNames,
        JSONObject dataRow) throws JSONException {
    // initialise the query by clearing out any previous parameters
    preparedStatement.clearBindings();

    // index used to bind parameters to the prepared statement
    int paramIndex = 1;

    // DELETE statements only need the id field bound, other require all
    // fields
    if (type == TYPE_DELETED) {
        // assume the id field exists for a DELETE statement
        String value = dataRow.getString("deleted_id");
        preparedStatement.bindString(1, value);
    } else {
        // do this to optimise the Android code
        int fieldCount = fieldNames.length();

        // add items to prepared statement by iterating over the array
        for (int i = 0; i < fieldCount; i++) {
            String fieldName = fieldNames.getString(i);

            // exclude some columns from the update
            if (includeFieldInUpdates(fieldName)) {
                // get data from JSON and add as parameter
                preparedStatement.bindString(paramIndex++, dataRow.getString(fieldName));
            }
        }
    }
}

From source file:com.dm.wallpaper.board.databases.Database.java

public void addCategories(List<WallpaperJson> categories) {
    String query = "INSERT INTO " + TABLE_CATEGORIES + " (" + KEY_NAME + "," + KEY_THUMB_URL
            + ") VALUES (?,?);";
    SQLiteDatabase db = this.getWritableDatabase();
    SQLiteStatement statement = db.compileStatement(query);
    db.beginTransaction();//from w ww  .j  av a2 s  .  c o m

    for (int i = 0; i < categories.size(); i++) {
        statement.clearBindings();
        statement.bindString(1, categories.get(i).name);
        statement.bindString(2, categories.get(i).thumbUrl == null ? "" : categories.get(i).thumbUrl);
        statement.execute();
    }
    db.setTransactionSuccessful();
    db.endTransaction();
    db.close();
}

From source file:com.dm.wallpaper.board.databases.Database.java

public void addWallpapers(@NonNull List<Wallpaper> wallpapers) {
    String query = "INSERT INTO " + TABLE_WALLPAPERS + " (" + KEY_NAME + "," + KEY_AUTHOR + "," + KEY_URL + ","
            + KEY_THUMB_URL + "," + KEY_CATEGORY + "," + KEY_ADDED_ON + ") VALUES (?,?,?,?,?,?);";
    SQLiteDatabase db = this.getWritableDatabase();
    SQLiteStatement statement = db.compileStatement(query);
    db.beginTransaction();// w  ww.j  a va  2 s.com

    for (int i = 0; i < wallpapers.size(); i++) {
        statement.clearBindings();
        statement.bindString(1, wallpapers.get(i).getName());
        statement.bindString(2, wallpapers.get(i).getAuthor());
        statement.bindString(3, wallpapers.get(i).getUrl());
        statement.bindString(4, wallpapers.get(i).getThumbUrl());
        statement.bindString(5, wallpapers.get(i).getCategory());
        statement.bindString(6, TimeHelper.getLongDateTime());
        statement.execute();
    }
    db.setTransactionSuccessful();
    db.endTransaction();
    db.close();
}

From source file:com.dm.wallpaper.board.databases.Database.java

public void addWallpapers(@NonNull WallpaperJson wallpaper) {
    String query = "INSERT INTO " + TABLE_WALLPAPERS + " (" + KEY_NAME + "," + KEY_AUTHOR + "," + KEY_URL + ","
            + KEY_THUMB_URL + "," + KEY_CATEGORY + "," + KEY_ADDED_ON + ") VALUES (?,?,?,?,?,?);";
    SQLiteDatabase db = this.getWritableDatabase();
    SQLiteStatement statement = db.compileStatement(query);
    db.beginTransaction();//from w  w  w. j  a  va 2s  .  com

    for (int i = 0; i < wallpaper.getWallpapers.size(); i++) {
        statement.clearBindings();
        statement.bindString(1, wallpaper.getWallpapers.get(i).name);
        statement.bindString(2, wallpaper.getWallpapers.get(i).author);
        statement.bindString(3, wallpaper.getWallpapers.get(i).url);
        statement.bindString(4,
                wallpaper.getWallpapers.get(i).thumbUrl == null ? wallpaper.getWallpapers.get(i).url
                        : wallpaper.getWallpapers.get(i).thumbUrl);
        statement.bindString(5, wallpaper.getWallpapers.get(i).category);
        statement.bindString(6, TimeHelper.getLongDateTime());
        statement.execute();
    }
    db.setTransactionSuccessful();
    db.endTransaction();
    db.close();
}

From source file:com.android.messaging.datamodel.BugleDatabaseOperations.java

/**
 * Note this is not thread safe so callers need to make sure they own the wrapper + statements
 * while they call this and use the returned value.
 *///w w  w. j a v  a2s  .c  o m
@DoesNotRunOnMainThread
public static SQLiteStatement getQueryMessagesLatestMessageStatement(final DatabaseWrapper db,
        final String conversationId) {
    Assert.isNotMainThread();
    final SQLiteStatement query = db.getStatementInTransaction(
            DatabaseWrapper.INDEX_QUERY_MESSAGES_LATEST_MESSAGE, QUERY_MESSAGES_LATEST_MESSAGE_SQL);
    query.clearBindings();
    query.bindString(1, conversationId);
    return query;
}

From source file:com.android.messaging.datamodel.BugleDatabaseOperations.java

/**
 * Note this is not thread safe so callers need to make sure they own the wrapper + statements
 * while they call this and use the returned value.
 *//*from   w w w  . j  a v a 2s.  c o  m*/
@DoesNotRunOnMainThread
public static SQLiteStatement getQueryConversationsLatestMessageStatement(final DatabaseWrapper db,
        final String conversationId) {
    Assert.isNotMainThread();
    final SQLiteStatement query = db.getStatementInTransaction(
            DatabaseWrapper.INDEX_QUERY_CONVERSATIONS_LATEST_MESSAGE, QUERY_CONVERSATIONS_LATEST_MESSAGE_SQL);
    query.clearBindings();
    query.bindString(1, conversationId);
    return query;
}

From source file:org.kontalk.provider.UsersProvider.java

private void addResyncContact(SQLiteDatabase db, SQLiteStatement stm, SQLiteStatement onlineUpd,
        SQLiteStatement onlineIns, String number, String jid, String displayName, String lookupKey,
        Long contactId, boolean registered) {

    int i = 0;//w ww .j  a  v  a2 s . com

    stm.clearBindings();
    stm.bindString(++i, number);
    stm.bindString(++i, jid);
    if (displayName != null)
        stm.bindString(++i, displayName);
    else
        stm.bindNull(++i);
    if (lookupKey != null)
        stm.bindString(++i, lookupKey);
    else
        stm.bindNull(++i);
    if (contactId != null)
        stm.bindLong(++i, contactId);
    else
        stm.bindNull(++i);
    stm.bindLong(++i, registered ? 1 : 0);
    stm.executeInsert();

    // update online entry
    i = 0;
    onlineUpd.clearBindings();
    onlineUpd.bindString(++i, number);
    if (displayName != null)
        onlineUpd.bindString(++i, displayName);
    else
        onlineUpd.bindNull(++i);
    if (lookupKey != null)
        onlineUpd.bindString(++i, lookupKey);
    else
        onlineUpd.bindNull(++i);
    if (contactId != null)
        onlineUpd.bindLong(++i, contactId);
    else
        onlineUpd.bindNull(++i);
    onlineUpd.bindString(++i, jid);
    int rows = executeUpdateDelete(db, onlineUpd);

    // no contact found, insert a new dummy one
    if (rows <= 0) {
        i = 0;
        onlineIns.clearBindings();
        onlineIns.bindString(++i, number);
        onlineIns.bindString(++i, jid);
        if (displayName != null)
            onlineIns.bindString(++i, displayName);
        else
            onlineIns.bindNull(++i);
        if (lookupKey != null)
            onlineIns.bindString(++i, lookupKey);
        else
            onlineIns.bindNull(++i);
        if (contactId != null)
            onlineIns.bindLong(++i, contactId);
        else
            onlineIns.bindNull(++i);
        onlineIns.bindLong(++i, registered ? 1 : 0);
        onlineIns.executeInsert();
    }
}

From source file:co.rewen.statex.StateXModule.java

/**
 * Inserts multiple (key, value) pairs. If one or more of the pairs cannot be inserted, this will
 * return StateXFailure, but all other pairs will have been inserted.
 * The insertion will replace conflicting (key, value) pairs.
 *//*  w ww .  j  av  a 2  s .  c  o m*/
@ReactMethod
public void multiSet(final ReadableArray keyValueArray, final Callback callback) {
    if (keyValueArray.size() == 0) {
        callback.invoke(AsyncStorageErrorUtil.getInvalidKeyError(null));
        return;
    }

    new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) {
        @Override
        protected void doInBackgroundGuarded(Void... params) {
            if (!ensureDatabase()) {
                callback.invoke(AsyncStorageErrorUtil.getDBError(null));
                return;
            }

            String sql = "INSERT OR REPLACE INTO " + TABLE_STATE + " VALUES (?, ?);";
            SQLiteStatement statement = mStateXDatabaseSupplier.get().compileStatement(sql);
            WritableMap error = null;
            ArrayList<String> keys = new ArrayList<>();
            try {
                mStateXDatabaseSupplier.get().beginTransaction();
                for (int idx = 0; idx < keyValueArray.size(); idx++) {
                    if (keyValueArray.getArray(idx).size() != 2) {
                        error = AsyncStorageErrorUtil.getInvalidValueError(null);
                        break;
                    }
                    String key = keyValueArray.getArray(idx).getString(0);
                    if (key == null) {
                        error = AsyncStorageErrorUtil.getInvalidKeyError(null);
                        break;
                    }
                    String value = keyValueArray.getArray(idx).getString(1);
                    if (value == null) {
                        error = AsyncStorageErrorUtil.getInvalidValueError(null);
                        break;
                    }

                    keys.add(key);
                    statement.clearBindings();
                    statement.bindString(1, key);
                    statement.bindString(2, value);
                    statement.execute();
                }
                mStateXDatabaseSupplier.get().setTransactionSuccessful();
            } catch (Exception e) {
                FLog.w(ReactConstants.TAG, e.getMessage(), e);
                error = AsyncStorageErrorUtil.getError(null, e.getMessage());
            } finally {
                try {
                    mStateXDatabaseSupplier.get().endTransaction();
                } catch (Exception e) {
                    FLog.w(ReactConstants.TAG, e.getMessage(), e);
                    if (error == null) {
                        error = AsyncStorageErrorUtil.getError(null, e.getMessage());
                    }
                }
            }
            if (error != null) {
                callback.invoke(error);
            } else {
                callback.invoke();
                notifyStateChanged(keys);
            }
        }
    }.execute();
}

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//from w  w  w  .  j av  a 2s. 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;
    }
}

From source file:mobile.tiis.appv2.base.BackboneApplication.java

public void updateChildVaccinationEventVaccinationAppointment(ChildCollector childCollector) {
    Child child = childCollector.getChildEntity();
    List<VaccinationEvent> vaccinationEvents = childCollector.getVeList();
    List<VaccinationAppointment> vaccinationAppointments = childCollector.getVaList();
    ContentValues childCV = new ContentValues();
    DatabaseHandler db = getDatabaseInstance();

    SQLiteDatabase db1 = db.getWritableDatabase();
    db1.beginTransactionNonExclusive();/*from  w ww . j a v  a  2  s  .  com*/
    try {
        String sql0 = "INSERT OR REPLACE INTO " + SQLHandler.Tables.CHILD + " ( "
                + SQLHandler.SyncColumns.UPDATED + ", " + SQLHandler.ChildColumns.ID + ","
                + SQLHandler.ChildColumns.BARCODE_ID + "," + SQLHandler.ChildColumns.FIRSTNAME1 + ","
                + SQLHandler.ChildColumns.FIRSTNAME2 + "," + SQLHandler.ChildColumns.LASTNAME1 + ","
                + SQLHandler.ChildColumns.BIRTHDATE + "," + SQLHandler.ChildColumns.GENDER + ","
                + SQLHandler.ChildColumns.TEMP_ID + "," + SQLHandler.ChildColumns.HEALTH_FACILITY + ","
                + SQLHandler.ChildColumns.DOMICILE + "," + SQLHandler.ChildColumns.DOMICILE_ID + ","
                + SQLHandler.ChildColumns.HEALTH_FACILITY_ID + "," + SQLHandler.ChildColumns.STATUS_ID + ","
                + SQLHandler.ChildColumns.BIRTHPLACE_ID + "," + SQLHandler.ChildColumns.NOTES + ","
                + SQLHandler.ChildColumns.STATUS + "," + SQLHandler.ChildColumns.MOTHER_FIRSTNAME + ","
                + SQLHandler.ChildColumns.MOTHER_LASTNAME + ","
                + SQLHandler.ChildColumns.CUMULATIVE_SERIAL_NUMBER + ","
                + SQLHandler.ChildColumns.CHILD_REGISTRY_YEAR + "," + SQLHandler.ChildColumns.MOTHER_TT2_STS
                + "," + SQLHandler.ChildColumns.MOTHER_VVU_STS + "," + SQLHandler.ChildColumns.PHONE
                + " ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        SQLiteStatement stmt0 = db1.compileStatement(sql0);
        stmt0.bindString(1, "1");
        stmt0.bindString(2, child.getId() == null ? "" : child.getId());
        stmt0.bindString(3, child.getBarcodeID() == null ? "" : child.getBarcodeID());
        stmt0.bindString(4, child.getFirstname1() == null ? "" : child.getFirstname1());
        stmt0.bindString(5, child.getFirstname2() == null ? "" : child.getFirstname2());
        stmt0.bindString(6, child.getLastname1() == null ? "" : child.getLastname1());
        stmt0.bindString(7, child.getBirthdate() == null ? "" : child.getBirthdate());
        stmt0.bindString(8, child.getGender() == null ? "" : child.getGender());
        stmt0.bindString(9, child.getTempId() == null ? "" : child.getTempId());
        stmt0.bindString(10, child.getHealthcenter() == null ? "" : child.getHealthcenter());
        stmt0.bindString(11, child.getDomicile() == null ? "" : child.getDomicile());
        stmt0.bindString(12, child.getDomicileId() == null ? "" : child.getDomicileId());
        stmt0.bindString(13, child.getHealthcenterId() == null ? "" : child.getHealthcenterId());
        stmt0.bindString(14, child.getStatusId() == null ? "" : child.getStatusId());
        stmt0.bindString(15, child.getBirthplaceId() == null ? "" : child.getBirthplaceId());
        stmt0.bindString(16, child.getNotes() == null ? "" : child.getNotes());
        stmt0.bindString(17, child.getStatus() == null ? "" : child.getStatus());
        stmt0.bindString(18, child.getMotherFirstname() == null ? "" : child.getMotherFirstname());
        stmt0.bindString(19, child.getMotherLastname() == null ? "" : child.getMotherLastname());
        stmt0.bindString(20, child.getChildCumulativeSn() == null ? "" : child.getChildCumulativeSn());
        stmt0.bindString(21, child.getChildRegistryYear() == null ? "" : child.getChildRegistryYear());
        stmt0.bindString(22, child.getMotherTT2Status() == null ? "" : child.getMotherTT2Status());
        stmt0.bindString(23, child.getMotherHivStatus() == null ? "" : child.getMotherHivStatus());
        stmt0.bindString(24, child.getPhone() == null ? "" : child.getPhone());
        stmt0.execute();
        stmt0.clearBindings();

        String sql = "INSERT OR REPLACE INTO " + SQLHandler.Tables.VACCINATION_EVENT + " ( "
                + SQLHandler.SyncColumns.UPDATED + ", " + SQLHandler.VaccinationEventColumns.APPOINTMENT_ID
                + "," + SQLHandler.VaccinationEventColumns.CHILD_ID + ","
                + SQLHandler.VaccinationEventColumns.DOSE_ID + ","
                + SQLHandler.VaccinationEventColumns.HEALTH_FACILITY_ID + ","
                + SQLHandler.VaccinationEventColumns.ID + "," + SQLHandler.VaccinationEventColumns.IS_ACTIVE
                + "," + SQLHandler.VaccinationEventColumns.MODIFIED_BY + ","
                + SQLHandler.VaccinationEventColumns.MODIFIED_ON + ","
                + SQLHandler.VaccinationEventColumns.NONVACCINATION_REASON_ID + ","
                + SQLHandler.VaccinationEventColumns.SCHEDULED_DATE + ","
                + SQLHandler.VaccinationEventColumns.VACCINATION_DATE + ","
                + SQLHandler.VaccinationEventColumns.VACCINATION_STATUS + ","
                + SQLHandler.VaccinationEventColumns.VACCINE_LOT_ID
                + " ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        SQLiteStatement stmt = db1.compileStatement(sql);

        for (VaccinationEvent vaccinationEvent : vaccinationEvents) {
            stmt.bindString(1, "1");
            stmt.bindString(2, vaccinationEvent.getAppointmentId());
            stmt.bindString(3, vaccinationEvent.getChildId());
            stmt.bindString(4, vaccinationEvent.getDoseId());
            stmt.bindString(5, vaccinationEvent.getHealthFacilityId());
            stmt.bindString(6, vaccinationEvent.getId());
            stmt.bindString(7, vaccinationEvent.getIsActive());
            stmt.bindString(8, vaccinationEvent.getModifiedBy());
            stmt.bindString(9, vaccinationEvent.getModifiedOn());
            stmt.bindString(10, vaccinationEvent.getNonvaccinationReasonId());
            stmt.bindString(11, vaccinationEvent.getScheduledDate());
            stmt.bindString(12, vaccinationEvent.getVaccinationDate());
            stmt.bindString(13, vaccinationEvent.getVaccinationStatus());
            stmt.bindString(14, vaccinationEvent.getVaccineLotId());
            stmt.execute();
            stmt.clearBindings();
        }

        String sql1 = "INSERT OR REPLACE INTO " + SQLHandler.Tables.VACCINATION_APPOINTMENT + " ( "
                + SQLHandler.SyncColumns.UPDATED + ", " + SQLHandler.VaccinationAppointmentColumns.CHILD_ID
                + "," + SQLHandler.VaccinationAppointmentColumns.ID + ","
                + SQLHandler.VaccinationAppointmentColumns.IS_ACTIVE + ","
                + SQLHandler.VaccinationAppointmentColumns.MODIFIED_BY + ","
                + SQLHandler.VaccinationAppointmentColumns.MODIFIED_ON + ","
                + SQLHandler.VaccinationAppointmentColumns.NOTES + ","
                + SQLHandler.VaccinationAppointmentColumns.OUTREACH + ","
                + SQLHandler.VaccinationAppointmentColumns.SCHEDULED_DATE + ","
                + SQLHandler.VaccinationAppointmentColumns.SCHEDULED_FACILITY_ID
                + " ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?,?)";

        SQLiteStatement stmt1 = db1.compileStatement(sql1);

        for (VaccinationAppointment vaccinationAppointment : vaccinationAppointments) {
            stmt1.bindString(1, "1");
            stmt1.bindString(2, vaccinationAppointment.getChildId());
            stmt1.bindString(3, vaccinationAppointment.getId());
            stmt1.bindString(4, vaccinationAppointment.getIsActive());
            stmt1.bindString(5, vaccinationAppointment.getModifiedBy());
            stmt1.bindString(6, vaccinationAppointment.getModifiedOn());
            stmt1.bindString(7, vaccinationAppointment.getNotes());
            stmt1.bindString(8, vaccinationAppointment.getOutreach());
            stmt1.bindString(9, vaccinationAppointment.getScheduledDate());
            stmt1.bindString(10, vaccinationAppointment.getScheduledFacilityId());

            stmt1.execute();
            stmt1.clearBindings();

        }

        db1.setTransactionSuccessful();
        db1.endTransaction();
    } catch (Exception e) {
        db1.endTransaction();
        e.printStackTrace();
    }
}