Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Android Query formulation with multiple conditions

I am writing an android application that is trying to pull data from a database based on two separate criteria.

The fields of workout and exercise are both strings in the database. I want to return a cursor with only those rows that satisfy BOTH criteria. Oh and I would also like it to be sorted in date order...

public Cursor graphQuery(String exercise, String workout) {
     Cursor cursor = mDb.query(DATABASE_TABLE, new String [] {KEY_DATE, KEY_REPS,       
         KEY_REPS_FEEL, KEY_WEIGHT, KEY_WEIGHT_FEEL}, "KEY_WORKOUT=" + workout + "AND" +  
         "KEY_EXERCISE=" + exercise, null , null, null, KEY_DATE); 

     return cursor;
}

I am a new android coder and would appreciate the help!

like image 320
easycheese Avatar asked Jun 13 '11 16:06

easycheese


1 Answers

Use selection and selectionArgs:

public Cursor graphQuery(String exercise, String workout) {
     Cursor cursor = mDb.query(DATABASE_TABLE, new String [] {KEY_DATE, KEY_REPS,       
         KEY_REPS_FEEL, KEY_WEIGHT, KEY_WEIGHT_FEEL}, "KEY_WORKOUT = ? AND KEY_EXERCISE = ?",
         new String[] { workout, exercise },
         null,
         null,
         KEY_DATE); 

     return cursor;
}

Notice how the selection String has ?s inplace of actual values and the actual values are passed in as a String[] and in the selectionArgs paramter. SQLite will replace those ?s with the values from the String[] selectionArgs.

like image 75
Steve Prentice Avatar answered Sep 28 '22 01:09

Steve Prentice