Example usage for android.database.sqlite SQLiteStatement close

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

Introduction

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

Prototype

public void close() 

Source Link

Document

Releases a reference to the object, closing the object if the last reference was released.

Usage

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   www.  j a  v a2  s  .  c om
 */
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./*  www .  j  a v  a2  s . c  o 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);//from   w w w . ja v  a  2s  .c  o  m
    stmt.bindDouble(3, targetPrice);
    stmt.bindString(4, reason);
    stmt.execute();
    stmt.close();

    db.close();

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

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());//from  w  w w . j a  v  a  2s  .c  o  m
        try {
            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:org.kontalk.provider.UsersProvider.java

private int executeUpdateDelete(SQLiteDatabase db, SQLiteStatement stm) {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
        return stm.executeUpdateDelete();
    } else {//from   w  w  w . j  a v  a  2 s.co m
        stm.execute();
        SQLiteStatement changes = db.compileStatement("SELECT changes()");
        try {
            return (int) changes.simpleQueryForLong();
        } finally {
            changes.close();
        }
    }
}

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

private SQLitePLuginResult doUpdateInBackgroundAndPossiblyThrow(String sql, String[] bindArgs,
        SQLiteDatabase db) {//from  w  w  w.j  a v  a 2s . c o m
    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.aquatest.dbinterface.tools.DatabaseUpdater.java

/**
 * Invoke web service to retrieve data, and then build and execute queries
 * to update local database/*from w  w w  . j a  v a 2  s.  com*/
 * 
 * @param type
 *            of rows to fetch (TYPE_ADDED, TYPE_UPDATED, TYPE_DELETED)
 * @param table
 *            table to request rows for
 * @return <code>true</code> if the method succeeds, <code>false</code> if
 *         the method fails
 * @throws ClientProtocolException
 * @throws JSONException
 *             if the data returned is not what was expected
 * @throws IOException
 */
private boolean fetchAndExecuteQueries(int type, String table)
        throws ClientProtocolException, JSONException, IOException {
    // Log.v("START", "fetchAndExecuteQueries(" + type + ", " + table +
    // ")");
    try {

        int count = 0;
        int totalCount = 1;
        int offset = 0;
        String status = "";
        JSONArray dataArray = null;
        boolean run = true;

        // determine JSON method to contact with our web service call
        String wsMethodName = "";
        switch (type) {
        case TYPE_ADDED:
            wsMethodName = AquaTestWebService.ADDED_ROWS;
            break;

        case TYPE_UPDATED:
            wsMethodName = AquaTestWebService.UPDATED_ROWS;
            break;

        case TYPE_DELETED:
            wsMethodName = AquaTestWebService.DELETED_ROWS;
            break;

        // TODO a default case should be added with error handling
        } // switch

        // this loop allows for paging of the data from the web service -
        // server returns max 1000 records at a time
        // TODO return fewer records at a time to save memory on the device?
        // e.g sample return string is almost 800,000 characters long
        while (((count + offset) < totalCount) && run) {
            // fetch data from web service
            // Log.v("DatabaseUpdater", "invoking web service [" +
            // wsMethodName + "] on table [" + table + "]");

            // java compiler optimises this "if" statement away based on
            // value of MOCK_WEB_SERVICES i.e. similar to C compiler #ifdef
            // blocks
            JSONObject jsonResponse;
            if (DebugConstants.MOCK_WEB_SERVICES) {
                // mock web services
                jsonResponse = MockAquaTestWebService.retrieveDataChanges(wsMethodName, table, lastUpdateTime,
                        (offset + count));
            } else {
                // use real production server
                jsonResponse = AquaTestWebService.retrieveDataChanges(wsMethodName, table, lastUpdateTime,
                        (offset + count));
            }

            // // Log.v("JSON_REQUEST", wsMethodName + " : " + table);

            // cancel update if so result was returned
            if (jsonResponse == null)
                return false;

            // interpret the JSON results
            //try {
            status = jsonResponse.getString(STATUS_KEY);
            //} catch (JSONException e) {

            //}

            if (status.compareTo(STATUS_SUCCESS) == 0) {
                // these fields allow for paging of the responses
                count = jsonResponse.getInt(COUNT_KEY);
                totalCount = jsonResponse.getInt(TOTAL_COUNT_KEY);
                offset = jsonResponse.getInt(OFFSET_KEY);

                // process the returned data
                if (count > 0 && jsonResponse.has(DATA_KEY)) {
                    // get the data array
                    dataArray = jsonResponse.getJSONArray(DATA_KEY);

                    // create the prepared sql statement
                    // FIXME this currently assumes that the first object
                    // contains all the field names needed
                    JSONArray dataFieldNames = dataArray.getJSONObject(0).names();
                    SQLiteStatement preparedStatement = generateQueryString(type, table, dataFieldNames);

                    try {
                        // do this to optimise the Android code
                        int dataLength = dataArray.length();

                        // loop over the returned data array
                        for (int i = 0; i < dataLength; i++) {
                            // check if thread has been cancelled
                            if (Thread.interrupted())
                                return false;

                            // get the current data record
                            JSONObject row = dataArray.getJSONObject(i);

                            // add parameters to the prepared statement
                            bindQueryParameters(preparedStatement, type, dataFieldNames, row);

                            // Log.v("SQL", "executing statement for data: "
                            // + row);

                            // execute the prepared statement
                            preparedStatement.execute();
                        } // for
                    } finally {
                        // release resources
                        preparedStatement.close();
                    }
                }
                // else exit
                else {
                    // Log.v("JSON", "empty or no data key: " + table + ", "
                    // + wsMethodName + "(" + offset + "," + count + ")");
                    run = false;
                } // else
            }
            // else the call failed, so do not continue
            else {
                // Log.v("DatabaseUpdater",
                // "web service call failed with status [" + status + "]");
                run = false;
            } // else

        } // while

        return true;
    } finally {
        // Log.v("END", "fetchAndExecuteQueries(" + type + ", " + table +
        // ")");
    }
}

From source file:io.requery.android.database.sqlite.SQLiteDatabase.java

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

From source file:io.requery.android.database.sqlite.SQLiteDatabase.java

/**
 * Utility method to run the query on the db and return the value in the
 * first column of the first row./*w w w  .  j  a  v  a  2  s.  c  om*/
 */
public String stringForQuery(String query, String[] selectionArgs) {
    SQLiteStatement prog = compileStatement(query);
    try {
        return stringForQuery(prog, selectionArgs);
    } finally {
        prog.close();
    }
}

From source file:io.requery.android.database.sqlite.SQLiteDatabase.java

/**
 * Utility method to run the query on the db and return the blob value in the
 * first column of the first row.//from ww w.jav  a  2s  .  co m
 *
 * @return A read-only file descriptor for a copy of the blob value.
 */
public ParcelFileDescriptor blobFileDescriptorForQuery(String query, String[] selectionArgs) {
    SQLiteStatement prog = compileStatement(query);
    try {
        return blobFileDescriptorForQuery(prog, selectionArgs);
    } finally {
        prog.close();
    }
}