Example usage for android.database.sqlite SQLiteStatement bindLong

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

Introduction

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

Prototype

public void bindLong(int index, long value) 

Source Link

Document

Bind a long value to this statement.

Usage

From source file:Main.java

/**
 * Binds the date or null to the statement on the given index.
 *
 * @param statement The statement./*from  w w  w  .  j  ava2 s.c o m*/
 * @param index     The index where the value will be bound.
 * @param value     The value to bind.
 */
public static void bindDateOrNull(SQLiteStatement statement, int index, @Nullable Date value) {
    if (value != null) {
        statement.bindLong(index, value.getTime());
    } else {
        statement.bindNull(index);
    }
}

From source file:Main.java

public static void bindValores(SQLiteStatement statement, ContentValues contentValues) {
    Set<String> chaves = new TreeSet<>(contentValues.keySet());
    int index = 1;

    for (String chave : chaves) {
        Object valor = contentValues.get(chave);

        if (valor == null) {
            statement.bindNull(index);/*ww  w .j av  a2s. c  o  m*/

        } else if (valor instanceof String) {
            statement.bindString(index, (String) valor);

        } else if (valor instanceof Double || valor instanceof Float) {
            statement.bindDouble(index, Double.valueOf(String.valueOf(valor)));

        } else if (valor instanceof Integer || valor instanceof Long) {
            statement.bindLong(index, Long.valueOf(String.valueOf(valor)));
        } else if (valor instanceof byte[]) {
            statement.bindBlob(index, (byte[]) valor);
        }
        index++;
    }
}

From source file:org.fitchfamily.android.wifi_backend.database.Database.java

private static SQLiteStatement bind(SQLiteStatement statement, AccessPoint accessPoint, int start) {
    if (!TextUtils.isEmpty(accessPoint.ssid())) {
        statement.bindString(start, accessPoint.ssid());
    }/*  w ww.  ja  va 2  s. c om*/
    statement.bindString(start + 1, String.valueOf(accessPoint.estimateLocation().latitude()));
    statement.bindString(start + 2, String.valueOf(accessPoint.estimateLocation().longitude()));
    statement.bindString(start + 3, String.valueOf(accessPoint.estimateLocation().radius()));
    statement.bindString(start + 4, String.valueOf(accessPoint.moveGuard()));
    statement.bindLong(start + 5, changedValue(accessPoint));
    bind(statement, accessPoint.sample(0), start + 6);
    bind(statement, accessPoint.sample(1), start + 8);
    bind(statement, accessPoint.sample(2), start + 10);
    return statement;
}

From source file:edu.stanford.mobisocial.dungbeetle.DBIdentityProvider.java

public List<RSAPublicKey> publicKeysForContactIds(List<Long> ids) {
    ArrayList<RSAPublicKey> result = new ArrayList<RSAPublicKey>(ids.size());
    SQLiteStatement s = mHelper.getReadableDatabase().compileStatement(
            "SELECT " + Contact.PUBLIC_KEY + " FROM " + Contact.TABLE + " WHERE " + Contact._ID + " = ?");
    for (Long id : ids) {
        s.bindLong(1, id.longValue());
        try {// w w w.  ja va  2s  . c o  m
            String pks = s.simpleQueryForString();
            result.add(RSACrypto.publicKeyFromString(pks));
        } catch (SQLiteDoneException e) {
            Log.e(TAG, "Data consisteny error: unknown contact id " + id);
        }
    }
    s.close();
    return result;
}

From source file:de.stadtrallye.rallyesoft.model.map.MapManager.java

private void updateDatabase(List<Node> nodes, List<Edge> edges) {
    SQLiteDatabase db = getDb();//  w ww  . jav a  2s  .  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.digicorp.plugin.sqlitePlugin.SQLitePlugin.java

/**
 * Executes a batch request and sends the results via sendJavascriptCB().
 *
 * @param dbname/*from ww  w.ja  v  a2  s. c o 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().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:com.zetaDevelopment.phonegap.plugin.sqlitePlugin.SQLitePlugin.java

/**
 * Executes a batch request and sends the results via sendJavascriptCB().
 *
 * @param dbname//  w ww . ja v  a2  s  . c o  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: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();/*w  w  w . j a va 2  s .  c om*/
    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 www.j  a  v  a2 s  . c  o  m
 *
 * @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.gimranov.zandy.app.task.APIRequest.java

/**
 * Saves the APIRequest's basic info to the database. Does not maintain handler information.
 * @param db/* ww w.  j a  v a  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;
    }
}