Example usage for android.database.sqlite SQLiteDatabase query

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

Introduction

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

Prototype

public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy,
        String having, String orderBy) 

Source Link

Document

Query the given table, returning a Cursor over the result set.

Usage

From source file:org.opendatakit.common.android.provider.impl.InstanceProviderImpl.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    List<String> segments = uri.getPathSegments();

    if (segments.size() < 2 || segments.size() > 3) {
        throw new SQLException("Unknown URI (too many segments!) " + uri);
    }// w  ww.ja va2 s.co m

    String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);
    String tableId = segments.get(1);
    String instanceName = null;
    // _ID in UPLOADS_TABLE_NAME
    String instanceId = (segments.size() == 3 ? segments.get(2) : null);

    SQLiteDatabase db = null;
    String fullQuery;
    String filterArgs[];
    Cursor c = null;

    String dbTableName;
    List<ColumnDefinition> orderedDefns;

    StringBuilder b = new StringBuilder();

    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        db.beginTransaction();

        boolean success = false;
        try {
            success = ODKDatabaseUtils.get().hasTableId(db, tableId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SQLException("Unknown URI (exception testing for tableId) " + uri);
        }
        if (!success) {
            throw new SQLException("Unknown URI (missing data table for tableId) " + uri);
        }

        dbTableName = "\"" + tableId + "\"";

        try {
            c = db.query(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME,
                    new String[] { KeyValueStoreColumns.VALUE },
                    KeyValueStoreColumns.TABLE_ID + "=? AND " + KeyValueStoreColumns.PARTITION + "=? AND "
                            + KeyValueStoreColumns.ASPECT + "=? AND " + KeyValueStoreColumns.KEY + "=?",
                    new String[] { tableId, KeyValueStoreConstants.PARTITION_TABLE,
                            KeyValueStoreConstants.ASPECT_DEFAULT, KeyValueStoreConstants.XML_INSTANCE_NAME },
                    null, null, null);

            if (c.getCount() == 1) {
                c.moveToFirst();
                int idxInstanceName = c.getColumnIndex(KeyValueStoreColumns.VALUE);
                instanceName = c.getString(idxInstanceName);
            }
        } finally {
            c.close();
        }

        // ARGH! we must ensure that we have records in our UPLOADS_TABLE_NAME
        // for every distinct instance in the data table.
        b.setLength(0);
        //@formatter:off
        b.append("INSERT INTO ").append(DatabaseConstants.UPLOADS_TABLE_NAME).append("(")
                .append(InstanceColumns.DATA_INSTANCE_ID).append(",")
                .append(InstanceColumns.DATA_TABLE_TABLE_ID).append(") ").append("SELECT ")
                .append(InstanceColumns.DATA_INSTANCE_ID).append(",")
                .append(InstanceColumns.DATA_TABLE_TABLE_ID).append(" FROM (").append("SELECT DISTINCT ")
                .append(DATA_TABLE_ID_COLUMN).append(" as ").append(InstanceColumns.DATA_INSTANCE_ID)
                .append(",").append("? as ").append(InstanceColumns.DATA_TABLE_TABLE_ID).append(" FROM ")
                .append(dbTableName).append(" EXCEPT SELECT DISTINCT ").append(InstanceColumns.DATA_INSTANCE_ID)
                .append(",").append(InstanceColumns.DATA_TABLE_TABLE_ID).append(" FROM ")
                .append(DatabaseConstants.UPLOADS_TABLE_NAME).append(")");
        //@formatter:on

        // TODO: should we collapse across FORM_ID or leave it this way?
        String[] args = { tableId };
        db.execSQL(b.toString(), args);

        // Can't get away with dataTable.* because of collision with _ID column
        // get map of (elementKey -> ColumnDefinition)
        try {
            orderedDefns = TableUtil.get().getColumnDefinitions(db, appName, tableId);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            throw new SQLException("Unable to retrieve column definitions for tableId " + tableId);
        }

        db.setTransactionSuccessful();
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }

    ////////////////////////////////////////////////////////////////
    // OK we have the info we need -- now build the query we want...

    // We can now join through and access the data table rows

    b.setLength(0);
    // @formatter:off
    b.append("SELECT ");
    b.append(DatabaseConstants.UPLOADS_TABLE_NAME).append(".").append(InstanceColumns._ID).append(" as ")
            .append(InstanceColumns._ID).append(",").append(DatabaseConstants.UPLOADS_TABLE_NAME).append(".")
            .append(InstanceColumns.DATA_INSTANCE_ID).append(" as ").append(InstanceColumns.DATA_INSTANCE_ID)
            .append(",").append(DatabaseConstants.UPLOADS_TABLE_NAME).append(".")
            .append(InstanceColumns.SUBMISSION_INSTANCE_ID).append(" as ")
            .append(InstanceColumns.SUBMISSION_INSTANCE_ID).append(",");
    // add the dataTable metadata except for _ID (which conflicts with InstanceColumns._ID)
    b.append(dbTableName).append(".").append(DataTableColumns.ROW_ETAG).append(" as ")
            .append(DataTableColumns.ROW_ETAG).append(",").append(dbTableName).append(".")
            .append(DataTableColumns.SYNC_STATE).append(" as ").append(DataTableColumns.SYNC_STATE).append(",")
            .append(dbTableName).append(".").append(DataTableColumns.CONFLICT_TYPE).append(" as ")
            .append(DataTableColumns.CONFLICT_TYPE).append(",").append(dbTableName).append(".")
            .append(DataTableColumns.FILTER_TYPE).append(" as ").append(DataTableColumns.FILTER_TYPE)
            .append(",").append(dbTableName).append(".").append(DataTableColumns.FILTER_VALUE).append(" as ")
            .append(DataTableColumns.FILTER_VALUE).append(",").append(dbTableName).append(".")
            .append(DataTableColumns.FORM_ID).append(" as ").append(DataTableColumns.FORM_ID).append(",")
            .append(dbTableName).append(".").append(DataTableColumns.LOCALE).append(" as ")
            .append(DataTableColumns.LOCALE).append(",").append(dbTableName).append(".")
            .append(DataTableColumns.SAVEPOINT_TYPE).append(" as ").append(DataTableColumns.SAVEPOINT_TYPE)
            .append(",").append(dbTableName).append(".").append(DataTableColumns.SAVEPOINT_TIMESTAMP)
            .append(" as ").append(DataTableColumns.SAVEPOINT_TIMESTAMP).append(",").append(dbTableName)
            .append(".").append(DataTableColumns.SAVEPOINT_CREATOR).append(" as ")
            .append(DataTableColumns.SAVEPOINT_CREATOR).append(",");
    // add the user-specified data fields in this dataTable
    for (ColumnDefinition cd : orderedDefns) {
        if (cd.isUnitOfRetention()) {
            b.append(dbTableName).append(".").append(cd.getElementKey()).append(" as ")
                    .append(cd.getElementKey()).append(",");
        }
    }
    b.append("CASE WHEN ").append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(" IS NULL THEN null")
            .append(" WHEN ").append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" IS NULL THEN null")
            .append(" WHEN ").append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(" > ")
            .append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" THEN null").append(" ELSE ")
            .append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" END as ")
            .append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(",");
    b.append("CASE WHEN ").append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(" IS NULL THEN null")
            .append(" WHEN ").append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" IS NULL THEN null")
            .append(" WHEN ").append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(" > ")
            .append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" THEN null").append(" ELSE ")
            .append(InstanceColumns.XML_PUBLISH_STATUS).append(" END as ")
            .append(InstanceColumns.XML_PUBLISH_STATUS).append(",");
    b.append("CASE WHEN ").append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(" IS NULL THEN null")
            .append(" WHEN ").append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" IS NULL THEN null")
            .append(" WHEN ").append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(" > ")
            .append(InstanceColumns.XML_PUBLISH_TIMESTAMP).append(" THEN null").append(" ELSE ")
            .append(InstanceColumns.DISPLAY_SUBTEXT).append(" END as ").append(InstanceColumns.DISPLAY_SUBTEXT)
            .append(",");
    if (instanceName == null) {
        b.append(DataTableColumns.SAVEPOINT_TIMESTAMP);
    } else {
        b.append(instanceName);
    }
    b.append(" as ").append(InstanceColumns.DISPLAY_NAME);
    b.append(" FROM ");
    b.append("( SELECT * FROM ").append(dbTableName).append(" AS T WHERE T.")
            .append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append("=(SELECT MAX(V.")
            .append(DATA_TABLE_SAVEPOINT_TIMESTAMP_COLUMN).append(") FROM ").append(dbTableName)
            .append(" AS V WHERE V.").append(DATA_TABLE_ID_COLUMN).append("=T.").append(DATA_TABLE_ID_COLUMN)
            .append(" AND V.").append(DATA_TABLE_SAVEPOINT_TYPE_COLUMN).append(" IS NOT NULL").append(")")
            .append(") as ").append(dbTableName);
    b.append(" JOIN ").append(DatabaseConstants.UPLOADS_TABLE_NAME).append(" ON ").append(dbTableName)
            .append(".").append(DATA_TABLE_ID_COLUMN).append("=").append(DatabaseConstants.UPLOADS_TABLE_NAME)
            .append(".").append(InstanceColumns.DATA_INSTANCE_ID).append(" AND ").append("? =")
            .append(DatabaseConstants.UPLOADS_TABLE_NAME).append(".")
            .append(InstanceColumns.DATA_TABLE_TABLE_ID);
    b.append(" WHERE ").append(DATA_TABLE_SAVEPOINT_TYPE_COLUMN).append("=?");
    // @formatter:on

    if (instanceId != null) {
        b.append(" AND ").append(DatabaseConstants.UPLOADS_TABLE_NAME).append(".").append(InstanceColumns._ID)
                .append("=?");
        String tempArgs[] = { tableId, InstanceColumns.STATUS_COMPLETE, instanceId };
        filterArgs = tempArgs;
    } else {
        String tempArgs[] = { tableId, InstanceColumns.STATUS_COMPLETE };
        filterArgs = tempArgs;
    }

    if (selection != null) {
        b.append(" AND (").append(selection).append(")");
    }

    if (selectionArgs != null) {
        String[] tempArgs = new String[filterArgs.length + selectionArgs.length];
        for (int i = 0; i < filterArgs.length; ++i) {
            tempArgs[i] = filterArgs[i];
        }
        for (int i = 0; i < selectionArgs.length; ++i) {
            tempArgs[filterArgs.length + i] = selectionArgs[i];
        }
        filterArgs = tempArgs;
    }

    if (sortOrder != null) {
        b.append(" ORDER BY ").append(sortOrder);
    }

    fullQuery = b.toString();

    db = null;
    boolean success = false;
    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        c = db.rawQuery(fullQuery, filterArgs);
        // Tell the cursor what uri to watch, so it knows when its source data
        // changes
        c.setNotificationUri(getContext().getContentResolver(), uri);
        success = true;
        return c;
    } finally {
        if (db != null && !success) {
            // leave database open for cursor...
            db.close();
        }
    }
}

From source file:com.openatk.fieldnotebook.MainActivity.java

private Field FindFieldById(Integer id) {
    if (id != null) {
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        // Find current field
        Field theField = null;//from  w w w .ja  va2  s .c  om
        String where = TableFields.COL_ID + " = " + Integer.toString(id) + " AND " + TableFields.COL_DELETED
                + " = 0";
        ;
        Cursor cursor = database.query(TableFields.TABLE_NAME, TableFields.COLUMNS, where, null, null, null,
                null);
        if (cursor.moveToFirst()) {
            theField = Field.cursorToField(cursor);
            theField.setMap(map);
        }
        cursor.close();
        dbHelper.close();
        return theField;
    } else {
        return null;
    }
}

From source file:com.openatk.fieldnotebook.MainActivity.java

private void drawFields() {
    SQLiteDatabase database = dbHelper.getReadableDatabase();
    String[] columns = { TableFields.COL_ID, TableFields.COL_BOUNDARY, TableFields.COL_NAME,
            TableFields.COL_DELETED };//  w w  w  . j a v  a2s  . co m
    String where = TableFields.COL_DELETED + " = 0";
    Cursor cursor = database.query(TableFields.TABLE_NAME, columns, where, null, null, null, null);
    FieldsOnMap = new ArrayList<Field>();
    while (cursor.moveToNext()) {
        String boundary = cursor.getString(cursor.getColumnIndex(TableFields.COL_BOUNDARY));
        List<LatLng> points = Field.StringToBoundary(boundary);

        if (points.size() == 0)
            points = null;

        // Add to list so we can catch click events
        Field newField = new Field();
        newField.setId(cursor.getInt(cursor.getColumnIndex(TableFields.COL_ID)));
        newField.setMap(map);
        newField.setBoundary(points);
        newField.setName(cursor.getString(cursor.getColumnIndex(TableFields.COL_NAME)));

        // Now draw this field
        // Create polygon
        if (points != null && points.isEmpty() == false) {
            PolygonOptions polygonOptions = new PolygonOptions();
            polygonOptions.fillColor(Field.FILL_COLOR_NOT_PLANNED);
            polygonOptions.strokeWidth(Field.STROKE_WIDTH);
            polygonOptions.strokeColor(Field.STROKE_COLOR);
            for (int i = 0; i < points.size(); i++) {
                polygonOptions.add(points.get(i));
            }
            newField.setPolygon(new MyPolygon(map, map.addPolygon(polygonOptions), this));
            if (currentField != null && newField.getId() == currentField.getId()) {
                this.currentPolygon = newField.getPolygon();
                this.currentPolygon.setLabel(newField.getName(), true);
            } else {
                newField.getPolygon().setLabel(newField.getName());
            }
        }
        FieldsOnMap.add(newField);
    }
    cursor.close();
    dbHelper.close();
    if (addIsShowing == 1) {
        if (this.currentPolygon != null && currentField != null) {
            this.currentPolygon.edit();
        }
        if (this.addingBoundary.length() > 0) {
            List<LatLng> points = Field.StringToBoundary(this.addingBoundary);
            this.currentPolygon = new MyPolygon(map, this);
            for (int i = 0; i < (points.size() - 1); i++) {
                this.currentPolygon.addPoint(points.get(i));
            }
        }
    }
}

From source file:edu.cens.loci.provider.LociDbUtils.java

/**
 * /*from w w w  .  j a va2  s .  co m*/
 * @param wifi
 * @return Recognition results with score higher than 0, sorted by score
 *              Recognition result contains Recognition time, PlaceId, FingerprintId, Score
 */
public ArrayList<RecognitionResult> getRecogntionScoresWifi(LociWifiFingerprint wifi) {
    ArrayList<RecognitionResult> results = new ArrayList<RecognitionResult>();

    final SQLiteDatabase db = mDbHelper.getReadableDatabase();

    checkPlaceTable();

    //checkDataTable();

    long mimeTypeId = mDbHelper.getMimeTypeId(WifiFingerprint.CONTENT_ITEM_TYPE);
    String selection = DataColumns.MIMETYPE_ID + "=" + mimeTypeId;
    Cursor cursor = db.query(Tables.DATA, WifiDataQuery.COLUMNS, selection, null, null, null,
            Data.PLACE_ID + " ASC");

    long recogTime = System.currentTimeMillis();
    if (cursor.moveToFirst()) {

        do {
            long placeId = cursor.getLong(WifiDataQuery.PLACEID);
            LociWifiFingerprint dbWifi;
            try {
                dbWifi = new LociWifiFingerprint(cursor.getString(WifiDataQuery.FINGERPRINT));
            } catch (JSONException e) {
                MyLog.e(LociConfig.D.JSON, TAG, "getRecognitionScoresWifi : json error.");
                e.printStackTrace();
                continue;
            }
            long timestamp = cursor.getLong(WifiDataQuery.TIMESTAMP);
            double score = recognitionAlgorithm(dbWifi, wifi);

            if (score > 0) {
                RecognitionResult result = new RecognitionResult(recogTime, placeId, timestamp, score);

                // sort the results by score, index 0 contains the highest score
                int resultsSize = results.size();
                for (int i = 0; i < resultsSize; i++) {
                    if (score > results.get(i).score) {
                        results.add(i, result);
                        break;
                    }
                }
                if (results.size() == resultsSize)
                    results.add(result);
            }
        } while (cursor.moveToNext());
    }
    cursor.close();

    MyLog.d(LociConfig.D.PD.SCORE, TAG, "[getRecognitionScoresWifi] #results=" + results.size());
    for (RecognitionResult result : results) {
        MyLog.d(LociConfig.D.PD.SCORE, TAG, result.toString());
    }

    return results;
}

From source file:com.renjunzheng.vendingmachine.MyGcmListenerService.java

private void updatePurchaseInfo(String purchaseInfo) {
    try {//from www.jav a2  s  .c o m
        DataDbHelper dbHelper = new DataDbHelper(this);
        SQLiteDatabase database = dbHelper.getWritableDatabase();

        database.delete(DataContract.PurchasedEntry.TABLE_NAME, null, null);
        database.execSQL(
                "DELETE FROM SQLITE_SEQUENCE WHERE NAME = '" + DataContract.PurchasedEntry.TABLE_NAME + "'");

        JSONArray valueArray = new JSONArray(purchaseInfo);
        Log.i(TAG, "the valueArray length: " + Integer.toString(valueArray.length()));
        for (int lc = 0; lc < valueArray.length(); ++lc) {
            JSONObject infoJson = valueArray.getJSONObject(lc);
            String item_name = infoJson.getString("item_name");
            database.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE NAME = '"
                    + DataContract.PurchasedEntry.TABLE_NAME + "'");

            //query based on this item_name and get item id
            //currently if queried has no such item in current database then don't insert to purchase table
            //find user id using the stored email
            Cursor itemIDCursor;
            int waitTime = 0;
            boolean breaked = false;
            do {
                String[] itemProj = new String[] { DataContract.ItemEntry._ID };
                String[] itemSelArgs = new String[] { item_name };
                itemIDCursor = database.query(DataContract.ItemEntry.TABLE_NAME, itemProj,
                        DataContract.ItemEntry.COLUMN_ITEM_NAME + " = ?", itemSelArgs, null, null, null);
                if (waitTime != 0) {
                    // if the item is not yet exists in the item table, probably means update purchase get called before update storage. So wait until find
                    SystemClock.sleep(1000);
                    if (++waitTime > 30) {
                        breaked = true;
                        break;
                    }
                } else if (waitTime == 0) {
                    waitTime = 1;
                }
            } while (itemIDCursor == null || itemIDCursor.getCount() == 0);

            if (!breaked) {
                itemIDCursor.moveToNext();
                int itemID = itemIDCursor.getInt(0);
                itemIDCursor.close();

                String[] userProj = new String[] { DataContract.UserEntry._ID };
                String user_email = infoJson.getString("email");
                String[] userSelArgs = new String[] { user_email };
                Cursor userIDCursor = database.query(DataContract.UserEntry.TABLE_NAME, userProj,
                        DataContract.UserEntry.COLUMN_EMAIL + " = ?", userSelArgs, null, null, null);
                userIDCursor.moveToNext();
                Log.i(TAG, "userID: " + user_email);
                int userID = userIDCursor.getInt(0);
                Log.i(TAG, "itemID: " + itemID);
                Log.i(TAG, "userID: " + userID);
                userIDCursor.close();
                ContentValues newValues = new ContentValues();
                newValues.put(DataContract.PurchasedEntry.COLUMN_ITEM_KEY, itemID);
                newValues.put(DataContract.PurchasedEntry.COLUMN_USER_KEY, userID);
                newValues.put(DataContract.PurchasedEntry.COLUMN_ORDER_TIME, infoJson.getString("order_time"));
                newValues.put(DataContract.PurchasedEntry.COLUMN_PICK_UP_TIME,
                        infoJson.getString("pickup_time"));
                newValues.put(DataContract.PurchasedEntry.COLUMN_QUANTITY, infoJson.getString("quantity"));
                newValues.put(DataContract.PurchasedEntry.COLUMN_RECEIPT_NUM, infoJson.getString("receipt"));
                Uri returnedUri = getContentResolver().insert(DataContract.PurchasedEntry.CONTENT_URI,
                        newValues);
                Log.i(TAG, "inserted row num " + ContentUris.parseId(returnedUri));
            }
        }

        database.close();
        dbHelper.close();
    } catch (JSONException e) {
        Log.e(TAG, "error when parsing Json");
    }
}

From source file:me.piebridge.bible.Bible.java

private void setMetadata(SQLiteDatabase metadata, String dataversion, boolean change) {
    Cursor cursor = metadata.query(Provider.TABLE_BOOKS, Provider.COLUMNS_BOOKS, null, null, null, null, null);
    if (change) {
        osiss.clear();// www .j a va2s . c om
        books.clear();
        chapters.clear();
        humans.clear();
    }
    try {
        while (cursor.moveToNext()) {
            String osis = cursor.getString(cursor.getColumnIndexOrThrow(Provider.COLUMN_OSIS));
            String book = cursor.getString(cursor.getColumnIndexOrThrow(Provider.COLUMN_HUMAN));
            String chapter = cursor.getString(cursor.getColumnIndexOrThrow(Provider.COLUMN_CHAPTERS));

            if (book.endsWith(" 1")) {
                book = book.substring(0, book.length() - 2);
            }
            if (!allhuman.containsKey(book)) {
                allhuman.put(book, osis);
            }

            Cursor cursor_chapter = null;
            // select group_concat(replace(reference_osis, "Gen.", "")) as osis from chapters where reference_osis like 'Gen.%';
            try {
                cursor_chapter = metadata.query(Provider.TABLE_CHAPTERS,
                        new String[] {
                                "group_concat(replace(reference_osis, \"" + osis + ".\", \"\")) as osis" },
                        "reference_osis like ?", new String[] { osis + ".%" }, null, null, null);
                if (cursor_chapter.moveToNext()) {
                    // we have only one column
                    chapter = cursor_chapter.getString(0);
                }
            } catch (Exception e) {
            } finally {
                if (cursor_chapter != null) {
                    cursor_chapter.close();
                }
            }
            if (change) {
                osiss.add(osis);
                books.add(book);
                chapters.add(chapter);
                humans.add(book);
            }
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    css = getVersionMetadata("css", metadata, "");
}

From source file:com.kyleszombathy.sms_scheduler.AddMessage.java

/** Pulls values from sql db on editMessage*/
private void retrieveAndUpdateMessageDataFromDB(int alarmNumber) {
    if (alarmNumber == -1)
        throw new IllegalArgumentException("alarmNumber cannot be -1");

    SQLDbHelper mDbHelper = new SQLDbHelper(AddMessage.this);
    SQLiteDatabase db = mDbHelper.getReadableDatabase();

    // Which row to update, based on the ID
    String selection = SQLContract.MessageEntry.ALARM_NUMBER + " LIKE ?";
    String[] selectionArgs = { String.valueOf(alarmNumber) };
    String[] projection = { SQLContract.MessageEntry.NAME, SQLContract.MessageEntry.MESSAGE,
            SQLContract.MessageEntry.PHONE, SQLContract.MessageEntry.YEAR, SQLContract.MessageEntry.MONTH,
            SQLContract.MessageEntry.DAY, SQLContract.MessageEntry.HOUR, SQLContract.MessageEntry.MINUTE,
            SQLContract.MessageEntry.PHOTO_URI };

    Cursor cursor = db.query(SQLContract.MessageEntry.TABLE_NAME, // The table to query
            projection, // The columns to return
            selection, // The columns for the WHERE clause
            selectionArgs, // The values for the WHERE clause
            null, // don't group the rows
            null, // don't filter by row groups
            null // The sort order
    );//w w  w  .  j a  v a  2s  . co m

    // Moves to first row
    cursor.moveToFirst();
    message.setNameList(Tools
            .stringToArrayList(cursor.getString(cursor.getColumnIndexOrThrow(SQLContract.MessageEntry.NAME))));
    message.setPhoneList(Tools
            .stringToArrayList(cursor.getString(cursor.getColumnIndexOrThrow(SQLContract.MessageEntry.PHONE))));
    message.setDateTime(cursor.getInt(cursor.getColumnIndexOrThrow(SQLContract.MessageEntry.YEAR)),
            cursor.getInt(cursor.getColumnIndexOrThrow(SQLContract.MessageEntry.MONTH)),
            cursor.getInt(cursor.getColumnIndexOrThrow(SQLContract.MessageEntry.DAY)),
            cursor.getInt(cursor.getColumnIndexOrThrow(SQLContract.MessageEntry.HOUR)),
            cursor.getInt(cursor.getColumnIndexOrThrow(SQLContract.MessageEntry.MINUTE)));
    message.setPhotoUriString(Tools.stringToArrayList(
            cursor.getString(cursor.getColumnIndexOrThrow(SQLContract.MessageEntry.PHOTO_URI))));
    message.setContent(cursor.getString(cursor.getColumnIndexOrThrow(SQLContract.MessageEntry.MESSAGE)));

    // Close everything so android doesn't complain
    cursor.close();
    mDbHelper.close();

    Log.d(TAG, "retrieveAndUpdateMessageDataFromDB: Values retrieved");
}

From source file:org.totschnig.myexpenses.provider.TransactionDatabase.java

@Override
public void onOpen(SQLiteDatabase db) {
    super.onOpen(db);
    //since API 16 we could use onConfigure to enable foreign keys
    //which is run before onUpgrade
    //but this makes upgrades more difficult, since then you have to maintain the constraint in
    //each step of a multi statement upgrade with table rename
    //we stick to doing upgrades with foreign keys disabled which forces us
    //to take care of ensuring consistency during upgrades
    if (!db.isReadOnly()) {
        db.execSQL("PRAGMA foreign_keys=ON;");
    }//from  w  ww.j  av  a2s .c o m
    try {
        db.delete(TABLE_TRANSACTIONS, KEY_STATUS + " = " + STATUS_UNCOMMITTED, null);
    } catch (SQLiteException e) {
        AcraHelper.report(e, DbUtils.getTableDetails(db.query("sqlite_master", new String[] { "name", "sql" },
                "type = 'table'", null, null, null, null)));
    }
}

From source file:com.openatk.field_work.MainActivity.java

public void loadOperations() {
    SQLiteDatabase database = dbHelper.getReadableDatabase();
    Cursor cursor = database.query(TableOperations.TABLE_NAME, TableOperations.COLUMNS, null, null, null, null,
            null);/*from w w  w  .j  a va 2 s. c om*/
    while (cursor.moveToNext()) {
        Operation operation = TableOperations.cursorToOperation(cursor);
        if (operation != null)
            operationsList.add(operation);
    }
    cursor.close();
    database.close();
    dbHelper.close();

    List<Operation> operations = dbHelper.readOperations();
    operationsList.clear();
    operationsList.addAll(operations);

    if (operations.isEmpty() == false) {
        //Add the "New Operation" button
        Operation operation = new Operation();
        operation.setName("New Operation");
        operationsList.add(operation);
    } else {
        //Dont display any operations
        //Hide?
    }

    if (spinnerMenuAdapter != null)
        spinnerMenuAdapter.notifyDataSetChanged();
    selectCurrentOperationInSpinner();
}

From source file:me.piebridge.bible.Bible.java

public String getHighlight(String osis) {
    highlightId = null;//from   w w w .jav a  2s  .  c  o m
    highlighted = "";
    SQLiteDatabase db = mOpenHelper.getReadableDatabase();
    if (!isDatabaseIntegrityOk(db)) {
        return highlighted;
    }
    Cursor cursor = null;
    try {
        cursor = db.query(AnnotationsDatabaseHelper.TABLE_ANNOTATIONS,
                new String[] { AnnotationsDatabaseHelper.COLUMN_ID, AnnotationsDatabaseHelper.COLUMN_VERSES },
                AnnotationsDatabaseHelper.COLUMN_OSIS + " = ? and " + AnnotationsDatabaseHelper.COLUMN_TYPE
                        + " = ?",
                new String[] { osis, "highlight" }, null, null, null);
        while (cursor != null && cursor.moveToNext()) {
            highlightId = cursor.getLong(0);
            highlighted = cursor.getString(1);
        }
    } catch (SQLiteException e) {
        e.printStackTrace();
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return highlighted;
}