Select data between two dates in a SQLite DB using a ContentResolver? - android

I have a DB in SQLite that saves the current date and time every time that the user inserts a new register. The date is stored in the db using the time string format: YYYY-MM-DD HH:MM:SS.
So the problem is that I need select the registers that are in a range between two dates and sort the result from lower to higher. I'm using my own content provider so, How can I achive this?
This is my Query code:
final String[] projection = {Contrato.Columnas._ID,Contrato.Columnas.SISTOLICA,Contrato.Columnas.DIASTOLICA,Contrato.Columnas.PULSO};
final String orderBy = Contrato.Columnas.SISTOLICA + " DESC";
Cursor c = resolver.query(Contrato.URI_CONTENIDO_BASE,projection,null,null,orderBy);

A ContentProvider is a façade. The meaning of any of the ContentProvider/ContentResolver API is up to you. So long as the client and the provider are in agreement over what parameters to things like query() mean, you can do whatever you want.
So, replace:
resolver.query(Contrato.URI_CONTENIDO_BASE,projection,null,null,orderBy)
with something like:
resolver.query(Contrato.URI_CONTENIDO_BASE,projection,Contrato.Columnas.SISTOLICA+">=? AND "+Contrato.Columnas.SISTOLICA+"<=?",args,orderBy)
where args are the two dates, in YYYY-MM-DD HH:MM:SS format. Probably, you can pass that stuff along to SQLite without modification. Even if you do need to modify it... again, it's your code, so you can make it do whatever you want.

Related

Android SQLite RawQuery not returning records with 2017 date

I have a database that contains upcoming births. The file has 5 records in it with due dates of (11-15-2016,10-15-2016, 12-14-2016, 12-13-2016 and 02-12-2017)
The query is
SQLiteDatabase db = dbhelper.getReadableDatabase();
String QueryPart1="SELECT inseminations._ID, inseminations.patient_id, inseminations.date_due ";
String QueryPart2="FROM inseminations ";
String QueryPart3="WHERE inseminations.date_due>=? ";
String QueryPart4="ORDER BY inseminations.date_due ASC";
String FinalQuery=QueryPart1+QueryPart2+QueryPart3+QueryPart4;
mCursor = db.rawQuery(FinalQuery ,howToFilter);'
howToFilter is
String howToFilter[]={ExpectedDateDue};
ExpectedDateDue is
ExpectedDateDue = new SimpleDateFormat("MM-dd-yyyy").format(new Date());
The query retrieves all records except for the one from 2017, the listview is sorted correctly, it's as if the query is only taking those records where the month is after the current month instead of the entire date.
Comparison operators on text in SQLite use lexicographic order. What this means, for example, is "01-01-2017" is less than "05-04-2016". SQLite has no indication that these strings represent moments in time that should be compared chronologically.
In general, I dislike using strings for timestamps in my databases for reasons like this. I much prefer to store timestamps as long values representing seconds (or milliseconds) since epoch. It's far easier to compare timestamps this way, and converting to and from date strings is simple enough either in SQLite or in Java.
If that's not feasible for some reason, then I suggest you alter the way you store your date strings in the database. Instead of MM-dd-yyyy, use yyyy-MM-dd. In this format, lexicographic comparisons will work; using the same example as before, "2017-01-01" is greater than "2016-05-04". Additionally, this format is acceptable as input to SQLite's various date and time functions, should you decide to use them.
If you can't alter the way the dates are stored, you will need to somehow convert them into a format that is comparable in the way you expect. You could use SQLite's substr() and || (concatenation) functions in the query to convert the date from MM-dd-yyyy to yyyy-MM-dd format. The code in this answer demonstrates this.

Android: SQLite Getting all records that inserted in last 7 days

Cursor cursor = db.rawQuery("SELECT * FROM expenses WHERE expense_date > (SELECT DATE('now', '-7 day'));", null);
I have this above query to get all records that inserted in last 7 days. But as a result of this query i am getting all the records. The date column of these records is inserted via Android's DatePicker and they are in 30-Jul-2015 format. I guess that's why this query does not work properly. Is there a way to make them consistent to get this query work properly or i am missing out something else ? Any help would be appreciated.
I've never tried using the SQLite built in date functions. Taking a quick look at the SQLite date function documentation here, it would seem that to use them the date needs to be in the format YYYY-MM-DD, which would be why your query is failing.
You can do some string manipulation/formatting before saving to the db and use that format.
Personally, I usually format in that manner but without the dash separators, then a simple less than/greater than comparison can be used, treating the date like a regular number. Of course some conversion back and forth is necessary for display, but for under the hood it works great.
int now = 20150730;
String query = "SELECT * FROM expenses WHERE expense_date > '" + now-7 + "'";

Android working with dates and SQLite

I am trying to create a simple reminder app. Im just logically thinking about the process. Basically I want to be able to choose a DAY and time e.g Monday 15:00, this will trigger EVERY Monday 15:00 until it gets deleted from database. Having said that example I have questions to accomplish this process.
How will I store DAY and TIME, what type, do I need different columns in my table?
How can I compare real time DAY to current DAY, so if its Monday real time it will return ONLY Monday reminders? is this possible?
Will I need to primarly focus using calendar?
As documentation says:
SQLite does not have a storage class set aside for storing dates
and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values.
You can store date and time in the TEXT type of field in the following format:
YYYY-MM-DD HH:MM:SS.SSS
and then use built-in date & time functions of SQLite to filter your records.
Another option is to store date & time as a time-stamp in milliseconds and write proper queries for selecting data or use Joda library for filtering or date & time transformation, but probably such solution would be less efficient and less convenient than first option.
Using integer column is the easiest solution.
Just store the date in millisecond (Calendar.getTimeInMillis()) and your good to go.
Then you just have to search on that integer to find the correct event in your database :
String selectQuery = "SELECT whateveryouneed FROM events WHERE date_event > ?";
Cursor c = db.rawQuery(selectQuery, new String[] { String.valueOf(calendar.getTimeInMillis())});
...
if you need to find all the event for a day , you just have to find the limits of the day in millisecond and make a query according to those limits

Using select method in SQL

I've added 3 strings of data into a SQL database in android. A fourth string makes up the database, however it is a date:
SimpleDateFormat outputDate = new SimpleDateFormat(yyyy-MM-dd)
Date outputDate = new Date();
When the user enters information to the database, the adding method for the database creates the date, which is added to the database.
My question is, how can I use these imported dates to create a method whereby only the rows in the database that were added on in the last 31 days?
A SELECT method comes to mind through research, but I don't know how to implement it?
Thanks
Presuming your database engine is SQLite, you should try something like that
SELECT * from your_table where julianday('now') - julianday(your_date_field)<=31;
You may be interested in SQLite date functions as well: http://www.sqlite.org/lang_datefunc.html
As long as you ask about Android I assume that the database you use is SQLite. SQLite does not have datatype for date. Thus you have couple of options: store the date in string (like you did) or store the timestamp of the date.
I seriously recommend you to use the second option as it is going to convert your dates in integers and it will be even easier to handle.
Thus when you want to select only events in the last 31 days you can do:
SQLiteDatabase database = helper.getWriteableDatabase();
final long millisIn31Days = 31 * 24 * 60 * 60 * 1000;
String where = "<your-date-column> >= ?"
String [] whereArgs = { String.valueOf(new Date().getTime() - millisIn31Days) };
Cursor cursor =
database.query("<TABLE_NAME>", null, where, whereArgs, null, null, null);
Note that here I write in angular brackets all the values you should actually fill in with the correct constants.
If you, however, want to stick to the string solution, you can still go with string comparison, as long as you specify the date format in correct manner (yours seems to be like that). In the string solution you will need to calculate the date of 31 days ago. You can use the Calendar's class auxiliary methods to achieve that.

SQL statement doesnt return value between two dates

I'm trying to select a specific date between two dates. The forma its stored in the DB is M/d/yyyy. What I'm trying to do, is passing two dates, and I want to select all data of a column between this two dates. I know there is data in the DB, but it doesnt bring anything for some dates.For some dates, it brings the data, but for some dates it brings the data.
Example:
When I choose 7/10/2011 as first date, and as second date 7/16/2011, it brings the data. But When I choose 7/9/2011 as first date and as second date 7/16/2011, it doesnt bring anything.
Here is my query:
Cursor cursor = db.query(CONTACT_DATA, new String[] { "duration" },
"date >= ? AND date <= ?",
new String[] { firstDate, secondDate }, null, null, null);
If anyone can help with this question. Thanks!
SQLite does not have a native date type; it is comparing your dates as strings. That's why when the dates are in the same month and year, and have the same number of digits in the day, the query appears to work, but that is just luck.
Typically SQLite users format their date strings using ISO-8601 format (YYYY-MM-DD) which sorts correctly as strings.
SQLite does have date functions -- if your dates are all well formed you may be able to use these, along with ltrim and rtrim to convert your dates to a format usable in queries.
I'm gonna store the dates as miliseconds(epoch format), so its easier to compare. And when printing the date, I'll convert it.

Categories

Resources