johnsonjp34 johnsonjp34 - 6 months ago 17
Android Question

Android Query Parameters

I'm using the query:

return mDB.query(DATABASE_TABLE, new String[] {
FIELD_ROW_ID,
FIELD_NAME, FIELD_LAT,
FIELD_LNG, FIELD_BEAR,
FIELD_BOOMWIDTH,
FIELD_COMMENTS, FIELD_ZOOM } , null, null, null, FIELDSELECTION , null);


The parameter hints say:

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


Parameters:

table

The table name to compile the query against.

columns

A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.

selection

A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.

selectionArgs

You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.

groupBy

A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.

having

A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used.

orderBy

How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.

QUESTION:

What actually goes in the groupBy and what goes in the having. I have a table with columns


  • FIELD_ROW_ID

  • FIELD_NAME

  • FIELD_LAT

  • FIELD_LNG

  • FIELD_BEAR

  • FIELD_BOOMWIDTH

  • FIELD_COMMENTS

  • FIELD_ZOOM.



I want to query all the results that have a certain FIELD_NAME selected by my spinner. The spinner passes the string of the particular
FIELD_NAME
as
FIELDSELECTION
and I need the query to just display the entire rows that have that
FIELDSELECTION
in a column. When I place anything other than null in the having parameter or groupBy parameter the application stops on the line of the query. Also, I'm not sure if the parameter string has to have GROUP BY or HAVING or if it already added automatically.

CL. CL.
Answer

The documentation assumes that you already know SQL.

This particular query would be written as:

 SELECT _id, Name, Lat, Lng, Bear, BoomWidth, Comments, Zoom
 FROM MyTable
 WHERE Name = (FIELDSELECTION)

This means that the comparison must go into the selection parameter:

mDB.query(DATABASE_TABLE,
          new String[] { FIELD_ROW_ID, FIELD_NAME, FIELD_LAT , FIELD_LNG, FIELD_BEAR, FIELD_BOOMWIDTH, FIELD_COMMENTS, FIELD_ZOOM },
          FIELD_NAME + " = ?", new String[] { FIELDSELECTION },
          null, null, null);
Comments