Android Database - behaving weird? - android

I want to have a search between specific dates. Say for example from the 1st of Aug 2012 to 13th Aug 2012. Search on this criteria gives me the entered value in the DB. If I make it 2nd Aug 2012, the query returns me null...Even weirder is that when I select 10th, 11th or the 12th Dates it works fine and gives me results...I have gone crazy trying to know where the issue could be and debug has not lead me any where....Help please?
/**query to get the details by giving all the dates/
public Cursor getName_Intime_Outtime_Date(String fromdate,String todate)
{
Log.d("pavan","in side the getnameintime out time date() of visistor adapter");
return this.db.query(DATABASE_TABLE_VISITOR,
new String[]{KEY_NAME,KEY_CHECKIN,KEY_CHECKOUT,KEY_DATE},
KEY_DATE + " BETWEEN ? AND ?",
new String[] {fromdate ,todate},
null, null, null, null);
}

Sqlite doesn't have a data type for dates. Probably you save your date as TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
I recommend you save date fields in your table as sqlLite datatype INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC, or as BIGINT (long java time version in miliseconds).
This way you would have a corect value returned when using BETWEEN with numbers.
EDIT
You can manage your date string from your query using date and time functions. This means you can still use your dates as strings, but performing casts to "DATE" using conversion functions when stringDates are used in sql WHERE clause.

try this, it is working for me, SELECT * FROM table_name
where substr(column_name,7)||substr(column_name,4,2)||substr(column_name,1,2)
between 'YYMMDD' and 'YYMMDD' , dates should be in reverse order eg: if date format is DD/MM/YY or DD-MM-YY , you can use 'YYMMDD'

Thank you guys for really looking into this...Finally solved this using idea found in this link https://groups.google.com/forum/?fromgroups#!topic/android-developers/Ey_4rBZx2t0%5B1-25%5D ....to summarize what I did was take a Calendar object, retrieve the current date using the Calendar object, the retrieved data is given to a simpledateformat object and comparisons to be made on that....Here is the sample code...
int test = date_pick.getMonth()+1;
Toast.makeText(getBaseContext(), "Date seleted month"+test+"/"+date_pick.getDayOfMonth()+"/"+date_pick.getYear(), Toast.LENGTH_LONG).show();
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.set(Calendar.YEAR, date_pick.getYear());
cal.set(Calendar.MONTH, test);
cal.set(Calendar.DAY_OF_MONTH, date_pick.getDayOfMonth());
/* retriving the yyyy mm dd values here*/
set_year = cal.get(Calendar.YEAR);
set_month= cal.get(Calendar.MONTH);
set_day = cal.get(Calendar.DAY_OF_MONTH);
Log.d("kunal","datesis "+set_year+" "+set_month+" "+set_day);
string_date = set_year+"-"+set_month+"-"+set_day;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
try {
d1 = sdf.parse(string_date);
Log.d("kunal","date came "+d1);
System.out.println(sdf.format(d1));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
date_txt.setText(sdf.format(d1));

Related

Same Milliseconds values coming for different dates

I store my values in database by converting the date value in milliseconds,so to get the latest date on top by using order by desc query. The order is coming as required but if i enter date 02/01/2016 and 01/30/2016 both are storing same milliseconds value.
String date = "02/01/2016";
String month = date.substring(0, 2);
String day = date.substring(3, 5);
String year = date.substring(6, 10);
Calendar c1 = Calendar.getInstance();
c1.set(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day));
long left = c1.getTimeInMillis();
After debugging i got the following milliseconds values
02/01/2016----61414914600000
and 01/30/2016----61414914600000
Anybody knows why this happening?
Using SimpleDateFormat value I am getting different milliseconds value:
Date date;
String dtStart = "02/01/2016";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
try {
date = format.parse(dtStart);
long timeMills=date.getTime();
System.out.println("Date ->" + date);
} catch (Exception e) {
e.printStackTrace();
}
I ran your initial code and it functions almost as expected. A few points:
You mention millisecond 61414914600000. That's not correct because it's 1900 years into the future:
http://currentmillis.com/?61414914600000
I'm pretty sure you got that number from a Date object, not from a Calendar: http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#Date(int, int, int)
As Mat said the month is zero-based for Calendar and the line where you call the setter should subtract 1:
c1.set(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day));
You answered your own question with another snippet of code but Date is deprecated, Calendar should be used instead. Your original code in the initial post was essentially correct (except the zero-based month). You should make sure that you know where your output is coming from and / or that you don't forget to build the code before running it.

Android - Time Comparison "hh:mm:ss a" format

"I try to compare two time in "hh:mm:ss a" format. But it not really work in what I think. I googled but couldn't find a proper answer. Sorry cause I'm new to programming."
I try to compare the time like this:
String strSQL = "SELECT * FROM " + TABLE_SCHEDULE + " WHERE lecturer_id=? AND schedule_day=? AND schedule_endtime > ?";
schedule_endtime > ?
However, the comparison has ignored the AM/PM which caused the result become like this:
eg. 12:00:00 PM is bigger than 02:00:00 PM.
Hope that you all can give some tips or provide some solution. Appreciate it.
Instead of comparing the formatted string, compare the value in milliseconds. Take a look at this to convert the string back to date:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String dateInString = "7-Jun-2013";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
Then once you have two dates you can compare them like so:
boolean before = someDate.before(anotherDate);
or
boolean after = someDate.after(anotherDate);
or even
someDate.getTime() < anotherDate.getTime();
Side note: when I store dates, I like to just store the millisecond value and the time zone. That way you don't need to worry about things like this.
Inside the SQLite database you are storing the dates as Strings, not as a Date because in SQLite doesn't exist a Date type (https://www.sqlite.org/datatype3.html).
You have two options: change the column type to a INTEGER type and store de date as a number (then you can compare milliseconds) or get the entity as it is, parse a Date type with the String, create a SimpleDateFormat with the given format and then make the comparison.

How do I only save date and not datetime in google datasource

I'm working on an android app with gae as backend. I have two queries around DateTime object com.google.gdata.data.DateTime
While inserting data, I only want to to insert date and not datetime. Here's current object creation and it saves both date and time.
stock.setDate(new DateTime(new Date()));
Also while retrieving stock object, where I have aggregated data, I want to group by date and not datetime. But as the data got stored as date and time, I'm getting group by datetime, where as I want date. What to do in such scenarios (yes, if we solve 1st problem this wont be required, but otherwise what should be done). My retrieval code is
List<AggregatedStock> execute = null;
PersistenceManager pm = getPersistenceManager();
Query query = pm
.newQuery(" select date, vehicleCode, vehicleSubCode, colorCode, sum(count) from Stock as AggregatedStock ");
query.setFilter(" updatedByDealer == " + dealer);
query.setGrouping(" date, vehicleCode, vehicleSubCode, colorCode ");
query.setOrdering(" vehicleCode desc ");
query.declareImports("import com.sandeepapplabs.dms.Stock");
try {
List<Object[]> results = (List<Object[]>) query.execute();
execute = new ArrayList<AggregatedStock>();
for (Object[] result : results) {
execute.add(new AggregatedStock((Date) result[0],
(String) result[1], (String) result[2],
(String) result[3], ((Long) result[4]).intValue()));
}
} finally {
pm.close();
}
return execute;
A Date is a single moment in time. It's a not a "day" that lasts 24 hours. When you call new Date(), you get a different moment - down to a millisecond - each time. Note that there is no difference here between Date and DateTime - the DateTime is simply a Date with a chronology.
You have three options if you want to use the "date as a day" to group your entities:
(a) Always set the date as a midnight (how to create a Java Date object of midnight today and midnight tomorrow?).
(b) Save it as new Date(), but extract the "day" portion or convert it into a String formatted to represent a calendar day before using it to group entities.
(c) Store and use dates as String values (i.e. "2014-12-24").
App Engine supports java.util.Date as a property. Complete list of supported value types can be found here

Android - Setting date to RelevantDate with an CursorAdapter

Let me just give an example of the requirements I am trying to fulfill. (Sorry if it's kind of a dumb question but my brain is a little fried right now and I'm working on this by myself)
I have a CursorAdapter (w/ SQLite on the backend) that I am using for my ListView to display content. One of the fields in the list item that I am displaying is the date the item was added to the Listview. So...
CASE:
If today was December 31st, 2013 and I just created a list item I would like it to display "Today". On January 1st, 2014 I would like the date to change to "Yesterday". And finally, on January 2nd, 2014 I would like the date to change to "12/31/2013".
What is the simple or most elegant way of fulfilling these requirements? I don't want to be constantly checking my whole listview for dates and be mean to the CPU. Any ideas on the best practice of saving the date would also be much appreciated!
Thanks!
I think I've got it working... I use this method in the activity where my listview is and call it every onCreate, onStart, and onResume.
public void setRelevantDate() {
SimpleDateFormat year = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
Date date = new Date();
String current_date = year.format(date);
String db_day_after_creation_date;
//check dates created, sub "today" or "yesterday"
for(SoundData s: app.unsent_recordings){
Log.e("soundData date flag",String.valueOf(s.isAfter_Day_two()));
Log.e("soundData date buffer",s.getDate_buffer());
Log.e("soundData date created",s.getDate_created());
if (!s.isAfter_Day_two()){ //if we are two days after the creation then we can skip all the checks for this item because
// it has already been set back to the initial MM/dd/yyyy date format
String sql_date = s.getDate_buffer();
String db_date = sql_date.substring(0,10);
String db_time = sql_date.substring(11);
//find the day after creation date
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(db_date));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DATE, 1);
db_day_after_creation_date = sdf.format(c.getTime());
if (db_date.equals(current_date)){
s.setDate_created("Today, "+db_time);
app.update_Recording_DateCreated(s.getId(),"Today, "+db_time, s.getDate_buffer(), String.valueOf(s.isAfter_Day_two())); //dateCreated = today, TIME
}
else if(current_date.equals(db_day_after_creation_date)){ // basically if the current date is equal to the day after the db_created date
s.setDate_created("Yesterday, "+db_time);
//we can say that it was created yesterday
app.update_Recording_DateCreated(s.getId(),"Yesterday, "+db_time, s.getDate_buffer(), String.valueOf(s.isAfter_Day_two()));
}
else{
s.setDate_created(sql_date);
//Otherwise use normal date
app.update_Recording_DateCreated(s.getId(),sql_date,s.getDate_buffer(), String.valueOf(s.isAfter_Day_two())); //dateCreated = dateBuffer
}
app.mCursor = app.db.getCursor();
app.rec_adapter.changeCursor(app.mCursor);
app.rec_adapter.notifyDataSetChanged(); //Update cursor, notifyDataSetChanged()
}

How to add a time stamp to every SQLDatabase update

I have a Database that when ever i put in information about things i want the database to show a time stamp with the information that i put in.
I'm assuming when you say "put in information" you're talking about an insert. If that's the case, you can just create a datetime column with the default of now in your schema:
DATETIME DEFAULT CURRENT_TIMESTAMP
You can also set it on your insert:
INSERT INTO your_database VALUES (datetime())
See here for more details:
How to insert a SQLite record with a datetime set to 'now' in Android application?
Good luck!
The simplest option might be to do it manually. Add an integer column and store System.currentTimeMillis() in that column.
EDIT
If you want to store it human readable create a text column. Then create the timestamp something like this
SimpleDateFormat sdf = new SimpleDateFormat("d MMM yyyy HH:mm:ss.S z");
Date now = new Date();
String timestamp = sdf.format(now);
which creates a String like this (you can change the format, check out the SimpleDateFormat documentation)
9 Dec 2011 23:06:05.849 EST
and if you are reading from the database you can do this to get a date object
Date then = null;
try {
then = sdf.parse(timestamp);
} catch (ParseException e) {
e.printStackTrace();
}
If you don't really care about the format you can just do
String timestamp = new Date().toString();
which will give output like
Fri Dec 09 23:06:05 EST 2011

Categories

Resources