Querying a Database

Each database query is returned as a Cursor. This lets Android manage resources more efficiently by retrieving and releasing row and column values on demand.

To execute a query on a database use the query method, passing in:

> An optional Boolean that specifies if the result set should contain only unique values.

> The name of the table to query.

> A projection, as an array of strings, that lists the columns to include in the result set.

> A "where" clause that defines the rows to be returned. You can include ? wildcards that will be replaced by the values passed in through the selection argument parameter.

> An array of selection argument strings that will replace the ?'s in the where clause.

> A "group by'' clause that defines how the resulting rows will be grouped.

> A "having" filter that defines which row groups to include if you specified a group by clause.

> A string that describes the order of the returned rows.

> An optional string that defines a limit for the number of returned rows. Listing 7-4 shows snippets for returning some, and all, of the rows in a particular table.

LISTING 7-4: Querying a database Available for download on // Return all rows for columns one and three, no duplicates Wrox.com String[] result_columns = new String[] {KEY_ID, KEY_COL1, KEY_COL3};

Cursor allRows = myDatabase.query(true, DATABASE_TABLE, result_columns, null, null, null, null, null, null);

// Return all columns for rows where column 3 equals a set value // and the rows are ordered by column 5. String where = KEY_COL3 + "=" + requiredValue; String order = KEY_COL5;

Cursor myResult = myDatabase.query(DATABASE_TABLE, null, where, null, null, null, order);

Mobile Apps Made Easy

Mobile Apps Made Easy

Quick start guide to skyrocket your offline and online business success with mobile apps. If you know anything about mobile devices, you’ve probably heard that famous phrase coined by one of the mobile device’s most prolific creators proclaiming that there’s an app for pretty much everything.

Get My Free Training Guide


Post a comment