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.
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...
you have two general option two do this Task
use row query **and
**use DISTINCT keyword
for using row query you can directly use function of mr.Sam
and for using DISTINCT keyword you can use
public Cursor query (boolean distinct, String table, String[] columns,
String selection, String[] selectionArgs, String groupBy,
String having, String orderBy, String limit)
because query stucher is retunsthis:
query(false, table, columns, selection, selectionArgs, groupBy,
having, orderBy, null /* limit */);
in this code first arg is for DISTINCT so provide it as true.
so your query will like this
Cursor cursor = db.query(true, YOUR_TABLE_NAME, new String[] { COLUMN1 ,COLUMN2, COLUMN_NAME_3 }, null, null, COLUMN2, null, null, null);
BasicallyDISTINCT keyword returns a column name only once if it apperase more then one time.
Related
I want to fetch record according to item_name..but it gives sql exception no such column: Roti exist.
query of my code is there
db.query(TABLE_1, new String[] { KEY_ITEM_CALORIES }, KEY_ITEM_NAME + "=" + item_name, null, null, null, null, null);
whats is the problem in this query?
you can make like that
Cursor mCursor=db.query(tablename, new String[] {"columnname1","columnname2"},"KEY_ITEM_NAME=?",new String[] { item_name }, null, null,null);
Try this
`Cursor cursor = db.rawQuery
("select * from Table_Name where Column_Name ='"+ value +"'", null)
I am using a content provider and need to query a table where one column of the row = thing1 and another column of that same row = thing2.
i know you can query a table for just one condition like:
Cursor c = contentResolver.query(content_uri, projection, variable + "='" + thing1 + "'", null, null);
now how can i query for two conditions? any help would be appreciated.
This should work:
Cursor c = contentResolver.query(content_uri, projection, "col1=? AND col2=?", args, null);
where args is a String[] of values to substitute in for the ? in the query.
Try this
Cursor c = contentResolver.query(content_uri, projection, variable + "='" + thing1 + "' AND "+variable2 + "='"+thing2+"'" , null, null);
I have a query that gets data from an sqlite database based on the Day value using a where clause, The data i'm getting is for 'Monday' this data is then populated into a listview. In addition to this i want to order the data by the time in ascending order to form a list with all events on monday from the earliest to latest Start times.
Query by day:
public Cursor getMonday () {
String Monday = "Monday";
return db.query(
DATABASE_TABLE,
new String[] { KEY_ID, KEY_LESSON, KEY_DAY, KEY_START, KEY_END, KEY_LOCATION},
KEY_DAY + "=?",
new String[] {Monday},
null, null, null);
}
I've tried:
public Cursor getMonday () {
String Monday = "Monday";
return db.query(DATABASE_TABLE,
new String[] {KEY_ID, KEY_LESSON, KEY_DAY, KEY_START,KEY_END, KEY_LOCATION},
KEY_DAY + "=?",
new String[] {Monday},
null, null, null,
KEY_START + " ASC");
}
This would usually work but i imagine that the WHERE clause and order by are not in the right order and i dont know how to make them work in unison. Could someone please advise? Thanks.
This is the error im getting:
01-28 14:24:02.738: E/AndroidRuntime(1672): FATAL EXCEPTION: main
01-28 14:24:02.738: E/AndroidRuntime(1672): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.unischeduler/com.example.unischeduler.ScheduleActivity}: java.lang.IllegalArgumentException: invalid LIMIT clauses:Start ASC
Your argument order is incorrect, try this:
public Cursor getMonday () {
String Monday = "Monday";
return db.query(DATABASE_TABLE,
new String[] {KEY_ID, KEY_LESSON, KEY_DAY, KEY_START,
KEY_END, KEY_LOCATION}, KEY_DAY + "=?",
new String[] {Monday}, null, null, KEY_START + " ASC", null);
}
EDIT Proposal to order by hh:mm format:
Take a look to SQLite Date and Time Functions and maybe you could try (I haven't tested it) something like this:
return db.query(DATABASE_TABLE,
new String[] {KEY_ID, KEY_LESSON, KEY_DAY, KEY_START,
KEY_END, KEY_LOCATION}, KEY_DAY + "=?",
new String[] {Monday}, null, null, "strftime('%H:%M', " + KEY_START + ")", null);
I have a SQlite database with some columns and with a content of an EditText I would like to select some rows from the database.
In main activity:
case R.id.betx:
String dates2 = sqletx.getText().toString();
GlobalVars.settables(dates2);
Intent intentstar2t = new Intent(dbhelp.this, CustomList.class);
startActivity(intentstar2t);
break;
This is my main activity, the 'dates2' String is the content of the edittext, and I save it for the setTables method.
My code in the hornot class where:
public Cursor getTable() {
String deda = GlobalVars.gettables();
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_HOTNESS,
KEY_CALORIE, KEY_MULTI, KEY_DATE};
return ourDatabase.query(DATABASE_TABLE, columns, KEY_DATE + "=" + deda ,
null, null, null, null);
}
Here I create a Cursor for the rows that fulfill the requirements in the last row. The String deda will be the 'dates2' we set before and I would like to get the rows where the KEY_DATE is equivalent to dates2.
The listview activity where I list the suitable rows.
if (todoItems.size() > 0) {
todoItems.clear();
}
if (list.size() > 0) {
list.clear();
}
Cursor c = info.getTable();
c = info.getTable();
if (c.moveToFirst())
{
do{
todoItems.add(c.getString(0) + " " + c.getString(1) + " " + c.getString(2)+ " " + c.getString(3)+ " " + c.getString(4));
quanitems.add(c.getString(4));
}
while (c.moveToNext());
}
if (todoItems.size() > 0)
{
for (int i=0; i<todoItems.size(); i++)
{
each=new EachRow();
each.text=(String) todoItems.get(i);
list.add(each);
each2=new EachRow();
each2.text=(String) quanitems.get(i);
list2.add(each2);
}
listView.setAdapter(new MyAdapter(this, 0, list));
}
I use a custom listview, in every row there are some items, but the point is that I create a cursor (c) for the rows where the KEY_DATE is equivalent to dates2.
My problem is I never define integer variable here, but if I create an entry where the date is for example "107" or "6519684" it is working, but if it is "tableOne" or any text it crushes at the row:
return ourDatabase.query(DATABASE_TABLE, columns, KEY_DATE + "=" + deda , null, null, null, null);
and
Cursor c = info.getTable();
(as you can see both problems are connected to the getTable method.
I use only Strings so practically the numbers ("107") are strings as well.
Any idea?
Thanks in advance!
use:
return ourDatabase.query(DATABASE_TABLE, columns, KEY_DATE + "=?" ,
new String[] { deda }, null, null, null);
Edit(explaination):
in query method you have String selection and String[] selectionArgs parameters, so in selection you can use ? for parameters in selectionArgs. Now underlying query builder will build query with this paramater and will apply proper escape chars.
I think that your query should be like this:
return ourDatabase.query(DATABASE_TABLE, columns, KEY_DATE + "= ?" ,
new String[] {deda}, null, null, null);
I've got an android app using a local sqlite database.
private SQLiteDatabase mDb;
when I run this query I get my Cursor over rows with pid equal to id, as desired:
mDb.query(true, PT_TABLE, new String[] {KEY_PID, KEY_TID},
KEY_PID+" = "+id, null, null, null, null, null);
when I run the following query, aiming to get that same result set, ordered by pid I get "android.database.sqlite.SQLiteException: datatype mismatch"
mDb.query(true, PT_TABLE, new String[] {KEY_PID, KEY_TID},
KEY_PID+" = "+id, null, null, null, null, KEY_PID+" DESC");
Any ideas?
It looks like you got just a little mixed up. According to the SQLiteDatabase.query documentation, the last argument is the LIMIT clause. The second to last is the ORDER BY clause.
Cursor query (boolean distinct,
String table,
String[] columns,
String selection,
String[] selectionArgs,
String groupBy,
String having,
String orderBy, // <-- ORDER BY
String limit)
EDIT
But, there is also another SQLiteDatabase.query where ORDER BY would be last
Cursor query (String table,
String[] columns,
String selection,
String[] selectionArgs,
String groupBy,
String having,
String orderBy)
This worked for me
String filter = MySQLiteHelper.JOB_ID + "=" + Integer.toString(jobID);
String orderBy = MySQLiteHelper.LOG_TIME + " DESC";
Cursor cursor = database.query(MySQLiteHelper.LOG_TABLE_NAME, logTableColumns,
filter, null, null, null, orderBy);
KEY_PID + " = " + "'" + id + "'"
Since Orderby is the second last parameter in the query;
your query would be like this
mDb.query(true, PT_TABLE, new String[] {KEY_PID, KEY_TID},
KEY_PID+" = "+id, null, null, null, KEY_PID+" DESC", null);
If I correctly understood your problem, try this.
String[] columns = new String[] {KEY_PID, KEY_TID};
String where = KEY_PID + " = " + Integer.toString(id);
String orderBy = KEY_PID + " DESC";
Cursor cursor = mDb.query(PT_TABLE, columns, where, null, null, null, orderBy);