Example usage for android.database.sqlite SQLiteDatabase compileStatement

List of usage examples for android.database.sqlite SQLiteDatabase compileStatement

Introduction

In this page you can find the example usage for android.database.sqlite SQLiteDatabase compileStatement.

Prototype

public SQLiteStatement compileStatement(String sql) throws SQLException 

Source Link

Document

Compiles an SQL statement into a reusable pre-compiled statement object.

Usage

From source file:com.xfinity.ceylon_steel.controller.CustomerController.java

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

        @Override/*from  ww  w  .  j av  a2  s  .  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:android.database.DatabaseUtils.java

/**
 * Utility method to run the query on the db and return the value in the
 * first column of the first row./*from   ww  w .  j  a  va2  s  .  c  o  m*/
 */
public static long longForQuery(SQLiteDatabase db, String query, String[] selectionArgs) {
    SQLiteStatement prog = db.compileStatement(query);
    try {
        return longForQuery(prog, selectionArgs);
    } finally {
        prog.close();
    }
}

From source file:android.database.DatabaseUtils.java

/**
 * Utility method to run the query on the db and return the value in the
 * first column of the first row./*from   w  w  w  .j av  a2s.  co  m*/
 */
public static String stringForQuery(SQLiteDatabase db, String query, String[] selectionArgs) {
    SQLiteStatement prog = db.compileStatement(query);
    try {
        return stringForQuery(prog, selectionArgs);
    } finally {
        prog.close();
    }
}

From source file:com.denimgroup.android.training.pandemobium.stocktrader.ManageTipsActivity.java

private void doSaveTip() {
    String symbol = etSymbol.getText().toString();
    Double targetPrice = Double.parseDouble(etTargetPrice.getText().toString());
    String reason = etReason.getText().toString();

    //   TOFIX - Read the username from the credentials.properties file

    String sql = "INSERT INTO tip (tip_creator, symbol, target_price, reason) VALUES (?, ?, ?, ?)";

    StockDatabase dbHelper = new StockDatabase(this.getApplicationContext());
    SQLiteDatabase db = dbHelper.openDatabase();
    SQLiteStatement stmt = db.compileStatement(sql);
    stmt.bindString(1, "USERNAME");
    stmt.bindString(2, symbol);/*  w ww .jav a2  s . c  o  m*/
    stmt.bindDouble(3, targetPrice);
    stmt.bindString(4, reason);
    stmt.execute();
    stmt.close();

    db.close();

    tvTipStatus.setText("Tip saved!");
}

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();//  www . j  av  a2s.c om

    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();//from  w ww  .java  2 s .c  o  m

    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  . jav a2 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:com.nolanlawson.cordova.sqlite.SQLitePlugin.java

private SQLitePLuginResult doUpdateInBackgroundAndPossiblyThrow(String sql, String[] bindArgs,
        SQLiteDatabase db) {
    debug("\"run\" query: %s", sql);
    SQLiteStatement statement = null;//from  w w  w  . j a  v a 2  s  .com
    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:org.fitchfamily.android.wifi_backend.database.Database.java

@Override
public void onOpen(SQLiteDatabase db) {
    super.onOpen(db);

    this.db = db;
    sqlSampleInsert = db.compileStatement(
            "INSERT INTO " + TABLE_SAMPLES + "(" + COL_RFID + ", " + COL_TYPE + ", " + COL_SSID + ", "
                    + COL_LATITUDE + ", " + COL_LONGITUDE + ", " + COL_RADIUS + ", " + COL_MOVED_GUARD + ", "
                    + COL_CHANGED + ", " + COL_LAT1 + ", " + COL_LON1 + ", " + COL_LAT2 + ", " + COL_LON2 + ", "
                    + COL_LAT3 + ", " + COL_LON3 + ") " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);");

    sqlSampleUpdate = db.compileStatement("UPDATE " + TABLE_SAMPLES + " SET " + COL_SSID + "=?, " + COL_LATITUDE
            + "=?, " + COL_LONGITUDE + "=?, " + COL_RADIUS + "=?, " + COL_MOVED_GUARD + "=?, " + COL_CHANGED
            + "=?, " + COL_LAT1 + "=?, " + COL_LON1 + "=?, " + COL_LAT2 + "=?, " + COL_LON2 + "=?, " + COL_LAT3
            + "=?, " + COL_LON3 + "=? " + "WHERE " + COL_RFID + "=?;");

    sqlAPdrop = db.compileStatement("DELETE FROM " + TABLE_SAMPLES + " WHERE " + COL_RFID + "=?;");
}

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

private void updateDatabase(List<Node> nodes, List<Edge> edges) {
    SQLiteDatabase db = getDb();

    db.beginTransaction();/*  w w  w .ja va 2  s  .  co m*/
    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();
    }
}