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:com.xfinity.ceylon_steel.controller.CustomerController.java

public static void downloadCustomers(final Context context) {
    new AsyncTask<User, Void, JSONArray>() {

        @Override/*  w  ww.j a  v  a2s. c o  m*/
        protected void onPreExecute() {
            if (UserController.progressDialog == null) {
                UserController.progressDialog = new ProgressDialog(context);
                UserController.progressDialog.setMessage("Downloading Data");
                UserController.progressDialog.setCanceledOnTouchOutside(false);
            }
            if (!UserController.progressDialog.isShowing()) {
                UserController.progressDialog.show();
            }
        }

        @Override
        protected JSONArray doInBackground(User... users) {
            try {
                User user = users[0];
                HashMap<String, Object> parameters = new HashMap<String, Object>();
                parameters.put("userId", user.getUserId());
                return getJsonArray(getCustomersOfUser, parameters, context);
            } catch (IOException ex) {
                Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
            } catch (JSONException ex) {
                Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
            }
            return null;
        }

        @Override
        protected void onPostExecute(JSONArray result) {
            if (UserController.atomicInteger.decrementAndGet() == 0 && UserController.progressDialog != null
                    && UserController.progressDialog.isShowing()) {
                UserController.progressDialog.dismiss();
                UserController.progressDialog = null;
            }
            if (result != null) {
                SQLiteDatabaseHelper databaseInstance = SQLiteDatabaseHelper.getDatabaseInstance(context);
                SQLiteDatabase database = databaseInstance.getWritableDatabase();
                SQLiteStatement compiledStatement = database
                        .compileStatement("replace into tbl_customer(customerId,customerName) values(?,?)");
                try {
                    database.beginTransaction();
                    for (int i = 0; i < result.length(); i++) {
                        JSONObject customer = result.getJSONObject(i);
                        compiledStatement.bindAllArgsAsStrings(
                                new String[] { Integer.toString(customer.getInt("customerId")),
                                        customer.getString("customerName") });
                        long response = compiledStatement.executeInsert();
                        if (response == -1) {
                            return;
                        }
                    }
                    database.setTransactionSuccessful();
                    Toast.makeText(context, "Customers downloaded successfully", Toast.LENGTH_SHORT).show();
                } catch (JSONException ex) {
                    Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
                    Toast.makeText(context, "Unable parse customers", Toast.LENGTH_SHORT).show();
                } finally {
                    database.endTransaction();
                    databaseInstance.close();
                }
            } else {
                Toast.makeText(context, "Unable to download customers", Toast.LENGTH_SHORT).show();
            }
        }

    }.execute(UserController.getAuthorizedUser(context));
}

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

/**
 * Execute SQL statement./*from w  w  w  .  j  a v  a 2 s.co m*/
 *
 * @param query
 *            The SQL query
 * @param params
 *            Parameters for the query
 * @param tx_id
 *            Transaction id
 */
public void executeSql(String query, String[] params, String tx_id) {
    String cmd = query.toLowerCase();

    try {
        if (cmd.startsWith("insert")) {
            SQLiteStatement myStatement = this.myDb.compileStatement(query);
            long insertId = myStatement.executeInsert();
            this.sendJavascript("dddb.completeQuery('" + tx_id + "', [{'insertId':'" + insertId
                    + "', 'rowsAffected':'1'}]);");
            /* Test fix for #22, requires API 11+: **
            } else if (cmd.startsWith("update") || cmd.startsWith("delete")) {
               SQLiteStatement myStatement = this.myDb.compileStatement(query);
               int rowsAffected = myStatement.executeUpdateDelete();
               this.sendJavascript("dddb.completeQuery('" + tx_id + "', [{'rowsAffected':'" + rowsAffected + "'}]);");
             * END of Test fix for #22, requires API 11+ */
        } else if (isDDL(query)) {
            this.myDb.execSQL(query);
            this.sendJavascript("dddb.completeQuery('" + tx_id + "', '');");
        } else {
            Cursor myCursor = this.myDb.rawQuery(query, params);
            this.processResults(myCursor, tx_id);
            myCursor.close();
        }
    } catch (SQLiteException ex) {
        ex.printStackTrace();
        System.out.println("SQLitePlugin.executeSql(): Error=" + ex.getMessage());

        // Send error message back to JavaScript
        this.sendJavascript("dddb.fail('" + ex.getMessage() + "','" + tx_id + "');");
    }
}

From source file:com.nolanlawson.cordova.sqlite.SQLitePlugin.java

private SQLitePLuginResult doUpdateInBackgroundAndPossiblyThrow(String sql, String[] bindArgs,
        SQLiteDatabase db) {/*  w w  w  .j  a  va  2  s .  c  om*/
    debug("\"run\" query: %s", sql);
    SQLiteStatement statement = null;
    try {
        statement = db.compileStatement(sql);
        debug("compiled statement");
        if (bindArgs != null) {
            statement.bindAllArgsAsStrings(bindArgs);
        }
        debug("bound args");
        if (isInsert(sql)) {
            debug("type: insert");
            long insertId = statement.executeInsert();
            int rowsAffected = insertId >= 0 ? 1 : 0;
            return new SQLitePLuginResult(EMPTY_ROWS, EMPTY_COLUMNS, rowsAffected, insertId, null);
        } else if (isDelete(sql) || isUpdate(sql)) {
            debug("type: update/delete");
            int rowsAffected = statement.executeUpdateDelete();
            return new SQLitePLuginResult(EMPTY_ROWS, EMPTY_COLUMNS, rowsAffected, 0, null);
        } else {
            // in this case, we don't need rowsAffected or insertId, so we can have a slight
            // perf boost by just executing the query
            debug("type: drop/create/etc.");
            statement.execute();
            return EMPTY_RESULT;
        }
    } finally {
        if (statement != null) {
            statement.close();
        }
    }
}

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

/**
 * Insert a message and its parts into the table
 *///from   w  w  w.j a  v  a 2  s  .  co m
@DoesNotRunOnMainThread
public static void insertNewMessageInTransaction(final DatabaseWrapper dbWrapper, final MessageData message) {
    Assert.isNotMainThread();
    Assert.isTrue(dbWrapper.getDatabase().inTransaction());

    // Insert message row
    final SQLiteStatement insert = message.getInsertStatement(dbWrapper);
    final long rowNumber = insert.executeInsert();

    Assert.inRange(rowNumber, 0, Long.MAX_VALUE);
    final String messageId = Long.toString(rowNumber);
    message.updateMessageId(messageId);
    //  Insert new parts
    for (final MessagePartData messagePart : message.getParts()) {
        messagePart.updateMessageId(messageId);
        insertNewMessagePartInTransaction(dbWrapper, messagePart, message.getConversationId());
    }
}

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

/**
 * Write a message part to our local database
 *
 * @param dbWrapper     The database//from ww w  .  ja  va 2  s .  c  o  m
 * @param messagePart   The message part to insert
 * @return The row id of the newly inserted part
 */
static String insertNewMessagePartInTransaction(final DatabaseWrapper dbWrapper,
        final MessagePartData messagePart, final String conversationId) {
    Assert.isTrue(dbWrapper.getDatabase().inTransaction());
    Assert.isTrue(!TextUtils.isEmpty(messagePart.getMessageId()));

    // Insert a new part row
    final SQLiteStatement insert = messagePart.getInsertStatement(dbWrapper, conversationId);
    final long rowNumber = insert.executeInsert();

    Assert.inRange(rowNumber, 0, Long.MAX_VALUE);
    final String partId = Long.toString(rowNumber);

    // Update the part id
    messagePart.updatePartId(partId);

    return partId;
}

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

private void updateDatabase(List<Node> nodes, List<Edge> edges) {
    SQLiteDatabase db = getDb();//ww  w .jav  a  2 s  . com

    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.zetaDevelopment.phonegap.plugin.sqlitePlugin.SQLitePlugin.java

/**
 * Executes a batch request and sends the results via sendJavascriptCB().
 *
 * @param dbname/*from  w  w w.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/*from   w  w w.j  a  v a  2 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: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 {/*from www . j a  v a 2 s.  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;/*  w  w w.  j  av  a  2s.co  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();
    }
}