Example usage for android.database.sqlite SQLiteStatement bindNull

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

Introduction

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

Prototype

public void bindNull(int index) 

Source Link

Document

Bind a NULL value to this statement.

Usage

From source file:Main.java

/**
 * Binds the string or null value to an statement.
 *
 * @param statement The statement./*from ww  w.  j  a v  a2 s.c  o  m*/
 * @param index     The index to bind.
 * @param value     The value to bind.
 */
public static void bindStringOrNull(SQLiteStatement statement, int index, @Nullable String value) {
    if (value != null) {
        statement.bindString(index, value);
    } else {
        statement.bindNull(index);
    }
}

From source file:Main.java

/**
 * Binds the date or null to the statement on the given index.
 *
 * @param statement The statement./*from  www.ja va 2  s. co 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);

        } 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);
        }//from  w w  w .  ja v  a 2s  .  c  o  m
        index++;
    }
}

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

/**
 * Executes a batch request and sends the results via sendJavascriptCB().
 *
 * @param dbname//from w w  w  .j  av a  2s  .  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: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;//ww  w  . j  a  va  2  s.  c  om

    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:de.stadtrallye.rallyesoft.model.chat.Chatroom.java

/**
 * Save ChatEntries to DB/*from   ww  w.  j a va 2 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/*from ww w .  j  a va  2  s  .  com*/
 */
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:com.ichi2.anki.SyncClient.java

private void updateFacts(JSONObject factsDict) {
    try {/*  www. j a va 2  s  .  c  o  m*/
        AnkiDb ankiDB = AnkiDatabaseManager.getDatabase(mDeck.getDeckPath());
        JSONArray facts = factsDict.getJSONArray("facts");
        int lenFacts = facts.length();

        if (lenFacts > 0) {
            JSONArray fields = factsDict.getJSONArray("fields");
            int lenFields = fields.length();

            // Grab fact ids
            // They will be used later to recalculate the count of facts and to delete them from DB
            ArrayList<String> factIds = new ArrayList<String>();
            for (int i = 0; i < lenFacts; i++) {
                factIds.add(facts.getJSONArray(i).getString(0));
            }
            String factIdsString = Utils.ids2str(factIds);

            // Recalculate fact count
            mDeck.setFactCount((int) (mDeck.getFactCount() + (lenFacts
                    - ankiDB.queryScalar("SELECT COUNT(*) FROM facts WHERE id IN " + factIdsString))));

            // Update facts
            String sqlFact = "INSERT OR REPLACE INTO facts (id, modelId, created, modified, tags, spaceUntil, lastCardId)"
                    + " VALUES(?,?,?,?,?,?,?)";
            SQLiteStatement statement = ankiDB.getDatabase().compileStatement(sqlFact);
            for (int i = 0; i < lenFacts; i++) {
                JSONArray fact = facts.getJSONArray(i);

                // id
                statement.bindLong(1, fact.getLong(0));
                // modelId
                statement.bindLong(2, fact.getLong(1));
                // created
                statement.bindDouble(3, fact.getDouble(2));
                // modified
                statement.bindDouble(4, fact.getDouble(3));
                // tags
                statement.bindString(5, fact.getString(4));
                // spaceUntil
                statement.bindDouble(6, fact.getDouble(5));
                // lastCardId
                if (!fact.isNull(6)) {
                    statement.bindLong(7, fact.getLong(6));
                } else {
                    statement.bindNull(7);
                }

                statement.execute();
            }
            statement.close();

            // Update fields (and delete first the local ones, since ids may have changed)
            ankiDB.getDatabase().execSQL("DELETE FROM fields WHERE factId IN " + factIdsString);

            String sqlFields = "INSERT INTO fields (id, factId, fieldModelId, ordinal, value) VALUES(?,?,?,?,?)";
            statement = ankiDB.getDatabase().compileStatement(sqlFields);
            for (int i = 0; i < lenFields; i++) {
                JSONArray field = fields.getJSONArray(i);

                // id
                statement.bindLong(1, field.getLong(0));
                // factId
                statement.bindLong(2, field.getLong(1));
                // fieldModelId
                statement.bindLong(3, field.getLong(2));
                // ordinal
                statement.bindString(4, field.getString(3));
                // value
                statement.bindString(5, field.getString(4));

                statement.execute();
            }
            statement.close();

            // Delete inserted facts from deleted
            ankiDB.getDatabase().execSQL("DELETE FROM factsDeleted WHERE factId IN " + factIdsString);
        }
    } catch (JSONException e) {
        Log.i(AnkiDroidApp.TAG, "JSONException = " + e.getMessage());
    }
}

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

private void mergeCardModels(String modelId, JSONArray cardModels) {
    ArrayList<String> ids = new ArrayList<String>();
    AnkiDb ankiDB = AnkiDatabaseManager.getDatabase(mDeck.getDeckPath());

    String sql = "INSERT OR REPLACE INTO cardModels (id, ordinal, modelId, name, description, active, qformat, "
            + "aformat, lformat, qedformat, aedformat, questionInAnswer, questionFontFamily, questionFontSize, "
            + "questionFontColour, questionAlign, answerFontFamily, answerFontSize, answerFontColour, answerAlign, "
            + "lastFontFamily, lastFontSize, lastFontColour, editQuestionFontFamily, editQuestionFontSize, "
            + "editAnswerFontFamily, editAnswerFontSize, allowEmptyAnswer, typeAnswer) "
            + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    SQLiteStatement statement = ankiDB.getDatabase().compileStatement(sql);
    int len = cardModels.length();
    for (int i = 0; i < len; i++) {
        try {/* www .j  a  va  2 s.  com*/
            JSONObject cardModel = cardModels.getJSONObject(i);

            // id
            String id = cardModel.getString("id");
            statement.bindString(1, id);
            // ordinal
            statement.bindString(2, cardModel.getString("ordinal"));
            // modelId
            statement.bindLong(3, cardModel.getLong("modelId"));
            // name
            statement.bindString(4, cardModel.getString("name"));
            // description
            statement.bindString(5, cardModel.getString("description"));
            // active
            statement.bindLong(6, Utils.booleanToInt(cardModel.getBoolean("active")));
            // qformat
            statement.bindString(7, cardModel.getString("qformat"));
            // aformat
            statement.bindString(8, cardModel.getString("aformat"));
            // lformat
            if (cardModel.isNull("lformat")) {
                statement.bindNull(9);
            } else {
                statement.bindString(9, cardModel.getString("lformat"));
            }
            // qedformat
            if (cardModel.isNull("qedformat")) {
                statement.bindNull(10);
            } else {
                statement.bindString(10, cardModel.getString("qedformat"));
            }
            // aedformat
            if (cardModel.isNull("aedformat")) {
                statement.bindNull(11);
            } else {
                statement.bindString(11, cardModel.getString("aedformat"));
            }
            // questionInAnswer
            statement.bindLong(12, Utils.booleanToInt(cardModel.getBoolean("questionInAnswer")));
            // questionFontFamily
            statement.bindString(13, cardModel.getString("questionFontFamily"));
            // questionFontSize
            statement.bindString(14, cardModel.getString("questionFontSize"));
            // questionFontColour
            statement.bindString(15, cardModel.getString("questionFontColour"));
            // questionAlign
            statement.bindString(16, cardModel.getString("questionAlign"));
            // answerFontFamily
            statement.bindString(17, cardModel.getString("answerFontFamily"));
            // answerFontSize
            statement.bindString(18, cardModel.getString("answerFontSize"));
            // answerFontColour
            statement.bindString(19, cardModel.getString("answerFontColour"));
            // answerAlign
            statement.bindString(20, cardModel.getString("answerAlign"));
            // lastFontFamily
            statement.bindString(21, cardModel.getString("lastFontFamily"));
            // lastFontSize
            statement.bindString(22, cardModel.getString("lastFontSize"));
            // lastFontColour
            statement.bindString(23, cardModel.getString("lastFontColour"));
            // editQuestionFontFamily
            if (cardModel.isNull("editQuestionFontFamily")) {
                statement.bindNull(24);
            } else {
                statement.bindString(24, cardModel.getString("editQuestionFontFamily"));
            }
            // editQuestionFontSize
            if (cardModel.isNull("editQuestionFontSize")) {
                statement.bindNull(25);
            } else {
                statement.bindString(25, cardModel.getString("editQuestionFontSize"));
            }
            // editAnswerFontFamily
            if (cardModel.isNull("editAnswerFontFamily")) {
                statement.bindNull(26);
            } else {
                statement.bindString(26, cardModel.getString("editAnswerFontFamily"));
            }
            // editAnswerFontSize
            if (cardModel.isNull("editAnswerFontSize")) {
                statement.bindNull(27);
            } else {
                statement.bindString(27, cardModel.getString("editAnswerFontSize"));
            }
            // allowEmptyAnswer
            if (cardModel.isNull("allowEmptyAnswer")) {
                cardModel.put("allowEmptyAnswer", true);
            }
            statement.bindLong(28, Utils.booleanToInt(cardModel.getBoolean("allowEmptyAnswer")));
            // typeAnswer
            statement.bindString(29, cardModel.getString("typeAnswer"));

            statement.execute();

            ids.add(id);
        } catch (JSONException e) {
            Log.i(AnkiDroidApp.TAG, "JSONException = " + e.getMessage());
        }
    }
    statement.close();

    // Delete card models that were not returned by the server
    ArrayList<String> cardModelsIds = ankiDB.queryColumn(String.class,
            "SELECT id FROM cardModels WHERE modelId = " + modelId, 0);

    for (String cardModelId : cardModelsIds) {
        if (!ids.contains(cardModelId)) {
            mDeck.deleteCardModel(modelId, cardModelId);
        }
    }
}

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

private void mergeFieldModels(String modelId, JSONArray fieldModels) {
    ArrayList<String> ids = new ArrayList<String>();
    AnkiDb ankiDB = AnkiDatabaseManager.getDatabase(mDeck.getDeckPath());

    String sql = "INSERT OR REPLACE INTO fieldModels VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    SQLiteStatement statement = ankiDB.getDatabase().compileStatement(sql);
    int len = fieldModels.length();
    for (int i = 0; i < len; i++) {
        try {//from w  w  w .j a v  a 2  s .c  o m
            JSONObject fieldModel = fieldModels.getJSONObject(i);

            // id
            String id = fieldModel.getString("id");
            statement.bindString(1, id);
            // ordinal
            statement.bindString(2, fieldModel.getString("ordinal"));
            // modelId
            statement.bindLong(3, fieldModel.getLong("modelId"));
            // name
            statement.bindString(4, fieldModel.getString("name"));
            // description
            statement.bindString(5, fieldModel.getString("description"));
            // features
            statement.bindString(6, fieldModel.getString("features"));
            // required
            statement.bindLong(7, Utils.booleanToInt(fieldModel.getBoolean("required")));
            // unique
            statement.bindLong(8, Utils.booleanToInt(fieldModel.getBoolean("unique")));
            // numeric
            statement.bindLong(9, Utils.booleanToInt(fieldModel.getBoolean("numeric")));
            // quizFontFamily
            if (fieldModel.isNull("quizFontFamily")) {
                statement.bindNull(10);
            } else {
                statement.bindString(10, fieldModel.getString("quizFontFamily"));
            }
            // quizFontSize
            if (fieldModel.isNull("quizFontSize")) {
                statement.bindNull(11);
            } else {
                statement.bindString(11, fieldModel.getString("quizFontSize"));
            }
            // quizFontColour
            if (fieldModel.isNull("quizFontColour")) {
                statement.bindNull(12);
            } else {
                statement.bindString(12, fieldModel.getString("quizFontColour"));
            }
            // editFontFamily
            if (fieldModel.isNull("editFontFamily")) {
                statement.bindNull(13);
            } else {
                statement.bindString(13, fieldModel.getString("editFontFamily"));
            }
            // editFontSize
            statement.bindString(14, fieldModel.getString("editFontSize"));

            statement.execute();

            ids.add(id);
        } catch (JSONException e) {
            Log.i(AnkiDroidApp.TAG, "JSONException");
        }
    }
    statement.close();

    // Delete field models that were not returned by the server
    ArrayList<String> fieldModelsIds = ankiDB.queryColumn(String.class,
            "SELECT id FROM fieldModels WHERE modelId = " + modelId, 0);

    for (String fieldModelId : fieldModelsIds) {
        if (!ids.contains(fieldModelId)) {
            mDeck.deleteFieldModel(modelId, fieldModelId);
        }
    }
}