Date order by with WHERE clause in Android - android

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);

Related

how to filter multiple data on multiple column sqlite database

i want to filter multiple data such as
id = "1,3,5" from columnid which is having 1 to 10 id
and another column such as name
name = "a,e,d" from name column of 10 records
and another criteria such as age
age = "21,23,20" from age column of 10 records from same table,
one example i got is
Cursor cursor = db.query("TABLE_NAME",new String[]{"ColumnName"}, "ColumnName=?",new String[]{"value"}, null, null, null);
which is just for one column but i want to get data from multiple column, can anyone help me?
try this working example,
Cursor cursor =
db.query(TABLE_DIARYENTRIES,
new String[] {},
STUDENT_ID + " IN ("+resultStudent+")"+ " AND " +CLASS_NAME + " IN ("+resultClass+")"
+ " AND " +SUBJECT_NAME + " IN ("+resultSubject+")"
null, null, null, null);
and your result string should be 'a','b','c'
I really like the way Google's example is structured. Because for noobies such as myself it makes it really clear what I am doing. And it is also more robust to SQL injections. Here is my modified version of the Google example:
//Column(s) I want returned
String[] projection = {"ColumnIWantReturned"};
//Column(s) I want to filer on
String selection = "FilterColumn1 IN (?) and FilterColumn2 IN (?, ?)";
String[] selectionArgs = {"ArgumentForFilterColumn1", "FirstArgumentForFilterColumn2", "SecondArgumentForFilterColumn2"};
Cursor cursor = db.query(
"MyTable", // The table to query
projection, // The array of columns to return (pass null to get all)
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // The sort order
);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Log.d("this-is-a-test", cursor.getString(0));
cursor.moveToNext();
}
cursor.close();

Query Content Resolver get all logs between two days

I want to create a query to a ContentResolver that will return all the call logs (name, number, photo) between a specified time, but it needs to be sorted by the number of counts.
A MySQL query would look like:
SELECT count(*) as counts, CallLog.Calls.CACHED_NAME,
CallLog.Calls.NUMBER, CallLog.Calls.CACHED_PHOTO_ID
FROM calls
WHERE CallLog.Calls.DATE > '2016-02-02' AND CallLog.Calls.DATE < '2016-02-04'
GROUP BY CallLog.Calls.CACHED_NAME order by counts DESC;
This is how I made the query, but I need also the group by and the order:
Cursor cur = .getContentResolver()
.query(callUri, null, CallLog.Calls.DATE + " BETWEEN ? AND ?", whereValue, null);
Can you please help me to add group by name and order by the count of each item?

How to query android call log data with group by date

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");

Multiple OrderBy in SQLiteDatabase.Query Method

I am using the query method of SQLiteDatabase. I need help with the orderBy parameter of this method.
Cursor cursor = sqLiteDatabase.query(tableName, tableColumns, whereClause, whereArgs, groupBy, having, orderBy);
public Cursor getAllCustomexp(int TID) throws SQLException
{
Cursor mCursor =
db.query(false, CEXP_TABLE, new String[] {KEY_CEID, FLD_CETID, FLD_CEEID, FLD_CEMID,
FLD_CEAMT, FLD_CESEL}, FLD_CETID + " = " + TID, null,
null, null, FLD_CEEID, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
Question 1:
In the above query the result set will be sorted by FLD_CEEID in ascending or descending order ?
Question 2:
If I need to order the result set first by FLD_CEEID and then by FLD_CEMID how should i construct the order by parameter of this query.
Is it possible to do multiple order by using this method?
From SQLite docs:
If a SELECT statement that returns more than one row does not have an
ORDER BY clause, the order in which the rows are returned is
undefined. Or, if a SELECT statement does have an ORDER BY clause,
then the list of expressions attached to the ORDER BY determine the
order in which rows are returned to the user. Rows are first sorted
based on the results of evaluating the left-most expression in the
ORDER BY list, then ties are broken by evaluating the second left-most
expression and so on. The order in which two rows for which all ORDER
BY expressions evaluate to equal values are returned is undefined.
Each ORDER BY expression may be optionally followed by one of the
keywords ASC (smaller values are returned first) or DESC (larger
values are returned first). If neither ASC or DESC are specified, rows
are sorted in ascending (smaller values first) order by default.
Answer 1: Result set will be sorted in ascending order.
Answer 2:
String orderBy = FLD_CEEID + " ASC, " + FLD_CEMID + " ASC";
db.query(false, CEXP_TABLE, new String[] {KEY_CEID, FLD_CETID, FLD_CEEID, FLD_CEMID,
FLD_CEAMT, FLD_CESEL}, FLD_CETID + " = " + TID, null,
null, null, orderBy, null);
It works like in SQL Select Order By. You can find details here: http://en.wikipedia.org/wiki/Order_by_(SQL) .

What is the sql query in SQLite, to retrieve the records from the database table for the last week, for the last month, and for the last year

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

Categories

Resources