Example usage for android.database.sqlite SQLiteStatement bindString

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

Introduction

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

Prototype

public void bindString(int index, String value) 

Source Link

Document

Bind a String value to this statement.

Usage

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 ww  w  .  j a  v  a  2 s .c o  m

    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:de.stadtrallye.rallyesoft.model.map.MapManager.java

private void updateDatabase(List<Node> nodes, List<Edge> edges) {
    SQLiteDatabase db = getDb();/*from  w w w  . jav a 2  s . c  o  m*/

    db.beginTransaction();
    try {
        db.delete(Edges.TABLE, null, null);
        db.delete(Nodes.TABLE, null, null);

        SQLiteStatement nodeIn = db.compileStatement("INSERT INTO " + Nodes.TABLE + " ("
                + DatabaseHelper.strStr(Nodes.COLS) + ") VALUES (?, ?, ?, ?, ?)");

        SQLiteStatement edgeIn = db.compileStatement(
                "INSERT INTO " + Edges.TABLE + " (" + DatabaseHelper.strStr(Edges.COLS) + ") VALUES (?, ?, ?)");

        for (Node n : nodes) {
            nodeIn.bindLong(1, n.nodeID);
            nodeIn.bindString(2, n.name);
            nodeIn.bindDouble(3, n.location.latitude);
            nodeIn.bindDouble(4, n.location.longitude);
            nodeIn.bindString(5, n.description);
            nodeIn.executeInsert();
        }

        for (Edge m : edges) {
            edgeIn.bindLong(1, m.nodeA.nodeID);
            edgeIn.bindLong(2, m.nodeB.nodeID);
            edgeIn.bindString(3, m.type.toString());
            edgeIn.executeInsert();
        }

        db.setTransactionSuccessful();
    } catch (Exception e) {
        Log.e(THIS, "Map Update on Database failed", e);
    } finally {
        db.endTransaction();
    }
}

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 ww  .j a  v  a 2  s  .com
@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.
 *///  w w  w.  j  av  a2  s  .co  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:com.zetaDevelopment.phonegap.plugin.sqlitePlugin.SQLitePlugin.java

/**
 * Executes a batch request and sends the results via sendJavascriptCB().
 *
 * @param dbname/*from  www .  j a  va  2s . co  m*/
 *            The name of the database.
 *
 * @param queryarr
 *            Array of query strings
 *
 * @param jsonparams
 *            Array of JSON query parameters
 *
 * @param queryIDs
 *            Array of query ids
 *
 * @param tx_id
 *            Transaction id
 *
 */
private void executeSqlBatch(String dbname, String[] queryarr, JSONArray[] jsonparams, String[] queryIDs,
        String tx_id) {
    SQLiteDatabase mydb = this.getDatabase(dbname);

    if (mydb == null)
        return;

    try {
        mydb.beginTransaction();

        String query = "";
        String query_id = "";
        int len = queryarr.length;

        for (int i = 0; i < len; i++) {
            query = queryarr[i];
            query_id = queryIDs[i];
            if (query.toLowerCase(Locale.getDefault()).startsWith("insert") && jsonparams != null) {
                SQLiteStatement myStatement = mydb.compileStatement(query);
                for (int j = 0; j < jsonparams[i].length(); j++) {
                    if (jsonparams[i].get(j) instanceof Float || jsonparams[i].get(j) instanceof Double) {
                        myStatement.bindDouble(j + 1, jsonparams[i].getDouble(j));
                    } else if (jsonparams[i].get(j) instanceof Number) {
                        myStatement.bindLong(j + 1, jsonparams[i].getLong(j));
                    } else {
                        myStatement.bindString(j + 1, jsonparams[i].getString(j));
                    }
                }
                long insertId = myStatement.executeInsert();

                String result = "{'insertId':'" + insertId + "'}";
                this.sendJavascriptCB("window.SQLitePluginTransactionCB.queryCompleteCallback('" + tx_id + "','"
                        + query_id + "', " + result + ");");
            } else {
                String[] params = null;

                if (jsonparams != null) {
                    params = new String[jsonparams[i].length()];

                    for (int j = 0; j < jsonparams[i].length(); j++) {
                        if (jsonparams[i].isNull(j))
                            params[j] = "";
                        else
                            params[j] = jsonparams[i].getString(j);
                    }
                }

                Cursor myCursor = mydb.rawQuery(query, params);

                if (query_id.length() > 0)
                    this.processResults(myCursor, query_id, tx_id);

                myCursor.close();
            }
        }
        mydb.setTransactionSuccessful();
    } catch (SQLiteException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } catch (JSONException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } finally {
        mydb.endTransaction();
        Log.v("executeSqlBatch", tx_id);
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txCompleteCallback('" + tx_id + "');");
    }
}

From source file:com.digicorp.plugin.sqlitePlugin.SQLitePlugin.java

/**
 * Executes a batch request and sends the results via sendJavascriptCB().
 *
 * @param dbname/* w  ww. ja va2  s  .c  om*/
 *            The name of the database.
 *
 * @param queryarr
 *            Array of query strings
 *
 * @param jsonparams
 *            Array of JSON query parameters
 *
 * @param queryIDs
 *            Array of query ids
 *
 * @param tx_id
 *            Transaction id
 *
 */
private void executeSqlBatch(String dbname, String[] queryarr, JSONArray[] jsonparams, String[] queryIDs,
        String tx_id) {
    SQLiteDatabase mydb = this.getDatabase(dbname);

    if (mydb == null)
        return;

    try {
        mydb.beginTransaction();

        String query = "";
        String query_id = "";
        int len = queryarr.length;

        for (int i = 0; i < len; i++) {
            query = queryarr[i];
            query_id = queryIDs[i];
            if (query.toLowerCase().startsWith("insert") && jsonparams != null) {
                SQLiteStatement myStatement = mydb.compileStatement(query);
                for (int j = 0; j < jsonparams[i].length(); j++) {
                    if (jsonparams[i].get(j) instanceof Float || jsonparams[i].get(j) instanceof Double) {
                        myStatement.bindDouble(j + 1, jsonparams[i].getDouble(j));
                    } else if (jsonparams[i].get(j) instanceof Number) {
                        myStatement.bindLong(j + 1, jsonparams[i].getLong(j));
                    } else if (jsonparams[i].isNull(j)) {
                        myStatement.bindNull(j + 1);
                    } else {
                        myStatement.bindString(j + 1, jsonparams[i].getString(j));
                    }
                }
                long insertId = myStatement.executeInsert();

                String result = "{'insertId':'" + insertId + "'}";
                this.sendJavascriptCB("window.SQLitePluginTransactionCB.queryCompleteCallback('" + tx_id + "','"
                        + query_id + "', " + result + ");");
            } else {
                String[] params = null;

                if (jsonparams != null) {
                    params = new String[jsonparams[i].length()];

                    for (int j = 0; j < jsonparams[i].length(); j++) {
                        if (jsonparams[i].isNull(j))
                            params[j] = "";
                        else
                            params[j] = jsonparams[i].getString(j);
                    }
                }

                Cursor myCursor = mydb.rawQuery(query, params);

                if (query_id.length() > 0)
                    this.processResults(myCursor, query_id, tx_id);

                myCursor.close();
            }
        }
        mydb.setTransactionSuccessful();
    } catch (SQLiteException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } catch (JSONException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } finally {
        mydb.endTransaction();
        Log.v("executeSqlBatch", tx_id);
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txCompleteCallback('" + tx_id + "');");
    }
}

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  v  a 2s .co m*/
    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:org.kontalk.provider.UsersProvider.java

private int insertKeys(ContentValues[] values) {
    SQLiteDatabase db = dbHelper.getWritableDatabase();

    int rows = 0;
    SQLiteStatement stm = db.compileStatement("INSERT OR REPLACE INTO " + TABLE_KEYS + " (" + Keys.JID + ", "
            + Keys.FINGERPRINT + ") VALUES(?, ?)");

    for (ContentValues v : values) {
        try {// www .ja  va  2s. co m
            stm.bindString(1, v.getAsString(Keys.JID));
            stm.bindString(2, v.getAsString(Keys.FINGERPRINT));
            stm.executeInsert();
            rows++;
        } catch (SQLException e) {
            Log.w(SyncAdapter.TAG, "error inserting trusted key [" + v + "]", e);
        }
    }

    return rows;
}

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;/*from w  ww  .  j  a  v  a  2  s.c o  m*/

    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: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 ava 2  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;
    }
}