Monday, May 21, 2018

display distinct records sqlite android



My cursor is returning records twice even though I set the distinct to true:



return myDataBase.query(true, DB_TABLE, new String[]
{"rowid as _id", KEY_CONDITIONS}, builder.toString(), symptoms, null, null, null, null);



FYI,



   public Cursor getData(String[] symptoms) {
String where = KEY_SYMPTOMS + "= ?";
String orStr = " OR ";

StringBuilder builder = new StringBuilder(where);
for(int i = 1; i < symptoms.length; i++)
builder.append(orStr).append(where);

return myDataBase.query(true, DB_TABLE, new String[]
{"rowid as _id", KEY_CONDITIONS}, builder.toString(), symptoms, null, null, null, null);

}


Or I tried to change to rawQuery



    return myDataBase.rawQuery("SELECT DISTINCT " + KEY_CONDITIONS + " FROM " 
+ DB_TABLE + " " + builder.toString() + symptoms.toString(), null);


My LogCat says:



  03-02 22:57:02.634: E/AndroidRuntime(333): FATAL EXCEPTION: main
03-02 22:57:02.634: E/AndroidRuntime(333): android.database.sqlite.SQLiteException: near "=": syntax error: , while compiling: SELECT DISTINCT conditions FROM tblSymptoms symptoms= ? OR symptoms= ?[Ljava.lang.String;@405550f8


Please help me identify what seems to be missing in here. Any help is truly appreciated.



enter image description here


Answer



Solution
You want DISTINCT conditions but Android requires the _id column which is a problem because you cannot mix and match: SELECT _id, DISTINCT condition.... However you can use the GROUP BY clause instead:



return myDataBase.query(DB_TABLE, new String[] {"rowid as _id", KEY_CONDITIONS}, 
builder.toString(), symptoms, KEY_CONDITIONS, null, null);





Explanations
This query:



return myDataBase.rawQuery("SELECT DISTINCT " + KEY_CONDITIONS + " FROM " 
+ DB_TABLE + " " + builder.toString() + symptoms.toString(), null);


Failed because you are passing String[] symptoms in the wrong parameter, try:



return myDataBase.rawQuery("SELECT DISTINCT " + KEY_CONDITIONS + " FROM " 
+ DB_TABLE + " " + builder.toString(), symptoms);





This query:



return myDataBase.query(true, DB_TABLE, new String[] {"rowid as _id", KEY_CONDITIONS}, builder.toString(), symptoms, null, null, null, null);


Failed because DISTINCT is looking at both the id and condition columns. It is the equivalent of: SELECT DISTINCT(_id, conditions) ... You, obviously, only want distinct conditions...


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...