I am querying call dates in call log database in android phone. After reading some articles, they said this needs to make some injection in my query method like this.
Cursor cursor = activity.getContentResolver().query(
CallLog.Calls.CONTENT_URI,
new String[] { CallLog.Calls.DATE},
"" + ") GROUP BY (" + CallLog.Calls.DATE,
null, CallLog.Calls.DATE + " DESC");
When I run my app and I got the following error message.
near ")": syntax error (code 1): , while compiling: SELECT date FROM calls WHERE ((() GROUP BY (date) AND ((type != 4)))) ORDER BY date DESC
Actually, I can't figure out how this query was built and why ((type !=4)) filter was appended to GROUP BY clause. I am currently using (compileSdkVersion 19, minSdkVersion 10 and targetSdkVersion 19). Is there any way to make raw query to Call Log Database because I want to write the query with my own to group dates.
CursorLoader cl = new CursorLoader(getActivity(), CallsQuery.CONTENT_URI, CallsQuery.PROJECTION, null, null, CallLog.Calls.DEFAULT_SORT_ORDER);
You can use the DEFAULT_SORT_ORDER which is date DESC
public static final String DEFAULT_SORT_ORDER
The default sort order for this table
Constant Value: `"date DESC"`
Just remove the extra brackets from your query and change it as below:
Cursor cursor =mActivity.getContentResolver().query(
CallLog.Calls.CONTENT_URI,
new String[] { CallLog.Calls.DATE},
" GROUP BY " + CallLog.Calls.DATE,null,CallLog.Calls.DATE + " DESC");
Related
I'm making an Android app and using a SQLite database. In particular I'm using the rawQuery method on a database obtained through a SQLiteOpenHelper. The query I build makes use of the ? marks as placeholders for the real values, which are passed along as an array of objects (e.g., select * from table where id = ?).
The question is, is it possible to get the query with the marks already replaced, at least from the cursor returned from the rawQuery method? I mean something like select * from table where id = 56. This would be useful for debugging purposes.
It's not possible. The ? values are not bound at the SQL level but deeper, and there's no "result" SQL after binding the values.
Variable binding is a part of the sqlite3 C API, and the Android SQLite APIs just provide a thin wrapper on top. http://sqlite.org/c3ref/bind_blob.html
For debugging purposes you can log your SQL with the ?, and log the values of your bind arguments.
You could form it as a string like this
int id = 56;
String query = "select * from table where id = '" + id + "'";
and then use it as a rawQuery like this (if I understood your question properly)
Cursor mCursor = mDb.rawQuery(query, null);
You can also use the SQLiteQueryBuilder. Here is an example with a join query:
//Create new querybuilder
SQLiteQueryBuilder _QB = new SQLiteQueryBuilder();
//Specify books table and add join to categories table (use full_id for joining categories table)
_QB.setTables(BookColumns.TABLENAME +
" LEFT OUTER JOIN " + CategoryColumns.TABLENAME + " ON " +
BookColumns.CATEGORY + " = " + CategoryColumns.FULL_ID);
//Order by records by title
_OrderBy = BookColumns.BOOK_TITLE + " ASC";
//Open database connection
SQLiteDatabase _DB = fDatabaseHelper.getReadableDatabase();
//Get cursor
Cursor _Result = _QB.query(_DB, null, null, null, null, null, _OrderBy);
I'm creating a database for my game, everything is working until I want to query one item.
I have been trying few different methods and I can't make it work. I just simply don't see the error in my code.
The code is as follows:
public Item getItem(String icon) {
String[] columns = {KEY_ID, KEY_TYPE, KEY_ICON, KEY_LEVEL, KEY_ARMOR, KEY_DAMAGE, KEY_BUY, KEY_SELL};
Cursor cursor = db.query(DB_TABLE, columns, KEY_ICON + "=" + icon,
null, null, null, null);
Item item=null;
if(cursor != null && cursor.moveToFirst()) {
item= new Item(cursor.getString(TYPE_COLUMN),
cursor.getString(ICON_COLUMN),
cursor.getString(LEVEL_COLUMN),
cursor.getString(ARMOR_COLUMN),
cursor.getString(DAMAGE_COLUMN),
cursor.getString(BUY_COLUMN),
cursor.getString(SELL_COLUMN)
);
}
return item;
}
The error I'm getting is
No such column: fast_boots (code 1): while compiling: SELECT id, type,
icon, level, armor, damage, buy, sell from items where icon=fast_boots
When trying to find .getItem("fast_boots"); I do see the fast_boots in my sql database
To make the query work, maybe you should try this :
KEY_ICON + "= '" + icon + "' "
As 'icon' is a string value. Since you're not specifying it, it is probably trying to understand it as being a column in the projection
This is the wrong way of implementing such functionality, though. Do not perform database queries on the getItem() method itself (main thread), it deserves to run in background, so it won't affect the main thread.
Please read about AsyncTask.
Try this
Cursor cursor = db.query(DB_TABLE, columns, KEY_ICON + "='" + icon +"'",
null, null, null, null);
I added '
I want to retrieve all the records in ascending order with a WHERE clause. But where to include the WHERE condition in my query? It is working fine for ascending order.
Here is my code. First I am working on this query but here I am not able to implement the ORDER BY clause.
Cursor tripdaycursor = sdb.rawQuery(
"select TripDay_Id, Tripday_Date, Tripday_ParsingDate,
Trip_Complete, TripDay_Endkm, TripDay_Count, Tripday_EndPlace
FROM TripDay WHERE Trip_Id="+record, null);
So I tried the code below for ascending order:
String recordid=Integer.toString(record), Trip_Id="Trip_Id", TripDay_Id="TripDay_Id",
Tripday_Date="Tripday_Date", Tripday_ParsingDate="Tripday_ParsingDate",
Trip_Complete="Trip_Complete", TripDay_Endkm="TripDay_Endkm",
TripDay_Count="TripDay_Count", Tripday_EndPlace="Tripday_EndPlace",
TripDay = "TripDay";
Cursor tripdaycursor = sdb.query(TripDay, new String[] {
TripDay_Id, Tripday_Date, Tripday_ParsingDate, Trip_Complete, TripDay_Endkm,
TripDay_Count, Tripday_EndPlace}, null, null, null, null,
Tripday_ParsingDate + " ASC");
But I want both conditions on a single query, with the WHERE clause and in ascending order. How to do that?
You can put "order by Column_Name" in your query after the where clause. Something like this, with the column you want to order by in ascending order
Cursor tripdaycursor = sdb.rawQuery("select TripDay_Id,Tripday_Date,Tripday_ParsingDate,Trip_Complete,TripDay_Endkm,TripDay_Count,Tripday_EndPlace from TripDay where Trip_Id="+record + " order by " + columnName,null);
At the moment i'm currently using the query builder to pull all my records from my database and they are currently organised by day however I its sorts in althabetical order,
public Cursor fetchAll() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_MODULECODE,
KEY_DAY, KEY_TIME, KEY_DURATION, KEY_TYPE, KEY_ROOM},null, null, null, null,"Day");
}
I know after some googling, that I need to replace the final section with a custom search order.
something along the lines of :
select _id, busnum,
case cast (strftime('%w', servdate) as integer)
when 0 then 'Sunday'
when 1 then 'Monday'
when 2 then 'Tuesday'
when 3 then 'Wednesday'
when 4 then 'Thursday'
when 5 then 'Friday'
else 'Saturday' end as servdayofweek
from tb1
where ...
From:
http://stackoverflow.com/questions/4319302/sqlite-return-as-day-of-week
so far i have been unable to figure out how tocombine the two and anyhelp in the right direction would be much aprechiated.
Edit Soloution
thank you for the help I went with declaring the string and linking to it in the query for anyone that needs something simple this is my final code for it
public Cursor fetchAll() {
String OrderBy ="case Day"+
" when 'Monday' then 0 "+
" when 'Tuesday' then 1"+
" when 'Wednesday' then 2"+
" when 'Thursday' then 3"+
" when 'Friday' then 5"+
" end";
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_MODULECODE,
KEY_DAY, KEY_TIME, KEY_DURATION, KEY_TYPE, KEY_ROOM},null, null, null, null,OrderBy );
}
If your Day values are the day names then you want something like this:
order by case Day
when 'Sunday' then 0
when 'Monday' then 1
when 'Tuesday' then 2
...
when 'Saturday' then 6
end
in the SQL; keep in mind that you can hand an SQL ORDER BY pretty much any expression. The orderBy argument to query can be any SQL ORDER BY clause (without the order by) so you want this big ugly string :
"case Day when 'Sunday' then 0 when 'Monday' then 1 ... when 'Saturday' then 6 end"
as the last argument to query. You'll have to properly fill in the ... of course.
If you cannot figure out how to pass a complex query through SQLiteDatabase.query(... lots of variables...) just pass your select statement as a string with SQLiteDatabase.rawQuery().
For example:
String query = "select _id, busnum, " +
" case cast cast (strftime('%w', servdate) as integer) " +
...
String[] selectionArgs = new String() { yada, yada, yada }
mDb.rawQuery(query, selectionArgs);
I created a data base table using SQLite in my project, I want to retrieve records from the database for the last week, for the last month, for the last year, when user click on the specified Buttons. But I don't know how to retrieve the records. Is there any function exist to get these records accordingly ?
You'll need to construct a "where" clause like so:
ContentResolver cr = getContentResolver();
Cursor groupCur = cr.query(
Groups.CONTENT_URI, // what table/content
new String [] {Groups._ID, Groups.NAME}, // what columns
"Groups.NAME NOT LIKE + 'System Group:%'", // where clause(s)
null, // ???
Groups.NAME + " ASC" // sort order
);
I spaced this out so it's easier to explain, but this is what you typically see as:
Cursor groupCur = cr.query(Groups.CONTENT_URI, null, null, null, null);
I found the query
SELECT * FROM DATABASE_TABLE
WHERE strftime('%Y-%m-%d',DATE) >= date('now','-6 days') AND
strftime('%Y-%m-%d',DATE)<=date('now') order by DATE