How to check if timepicker1 time is oldest than timepicker2 time? - android

i have to select a interval of time.
i have two timepickers on my app, i need to check if timepicker1 selected time is less than timepicker2 selected time. If not, i have to show a toast to told the user the error.
I also need to do this with two datepickers,not with times in that case, but with dates.
please can someone give me some code examples for do this?

You just need to compare the individual components of the date or time in the correct order. For time:
if (time1.getCurrentHour() < time2.getCurrentHour() || (time1.getCurrentHour() == time2.getCurrentHour() && time1.getCurrentMinute() < time1.getCurrentMinute())) {
//time 1 is earlier.
}
You might need to add in a bit of complexity depending on if you are showing 24 hour time or not.
For dates, its the same, just compare first the year then the month then the day.

Related

Best way to reset a database value every week on specific day (Android - Room)

I'm working on an Android app that has a functionality that is weekly basis, that is, every day of the week the user has to mark as done the day. This value is a boolean on my database, that is initialized with false, and is set to true when the user clicks on the checkbox. Everything is working fine.
But my problem is that I need to "reset" this boolean value to false on all the seven days of the week every time a new week begins. I don't need to have records of the past weeks. All that matters is the actual week (Sunday to Saturday).
It's a very simple task, I only need to do this:
for(WeekDay day: dao.getWeekDays()){
day.setDone(false);
dao.updateWeekDay(day); //update the value in database
}
So, I did some research (I'm new to android) and find out that Android has different schedule services like JobScheduler or AlarmManager. My app is designed to Android 10+ (API 29+).
What do you think is the best solution for my problem?
It's a very simple task (it won't take too much battery, internet,...) and I need to do this in a specific day (Sunday) every week. Also, this task needs to be done as soon as it possible, even if the phone is turned off on Sunday. It doesn't need to be a background service, but I need to guarantee that when the user opens the app and it's a new week, that method needs to be call before, but only if it had not been call in the actual week before.
Anyone has ideas?
Ok, I think I found a simple solution for my problem, based on other similar answers I read. I just need to run these function every time the app starts. I didn't need to use any background service, like WorkManager.
I only need to store in SharedPreferences the last date when the system did a reset in the values. Then, every time I open the app, it checks if today is in a different week from the last reset day. If it's true, then I run that "for cycle" in the question and update the last reset day to today in the SharedPreferences. If it's false, I do nothing.
The method inSameCalendarWeek checks if the day is in the same week from the same year of today (Locale.US guarantees that a week starts on Sunday. But I could change that to Locale.getDefault() to be more flexible). Also, for example, if December 31 is in the same week of January 1, even if they are in different years, the method will return true.
private void checkAndResetDoneDays() {
long lastResetDay = settings.getLong(LAST_DAY_RESET, 0);
LocalDate date = Instant.ofEpochMilli(lastResetDay).atZone(ZoneId.systemDefault()).toLocalDate();
if (!inSameCalendarWeek(date)) {
resetDoneDays();
settings.edit()
.putLong(LAST_DAY_RESET, LocalDate.now(ZoneId.systemDefault()).atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli())
.commit();
}
}
public boolean inSameCalendarWeek(LocalDate firstDate) {
LocalDate secondDate = LocalDate.now(ZoneId.systemDefault());
// get a reference to the system of calendar weeks in US Locale (to guarantee that week starts on Sunday)
WeekFields weekFields = WeekFields.of(Locale.US);
// find out the calendar week for each of the dates
int firstDatesCalendarWeek = firstDate.get(weekFields.weekOfWeekBasedYear());
int secondDatesCalendarWeek = secondDate.get(weekFields.weekOfWeekBasedYear());
/*
* find out the week based year, too,
* two dates might be both in a calendar week number 1 for example,
* but in different years
*/
int firstWeekBasedYear = firstDate.get(weekFields.weekBasedYear());
int secondWeekBasedYear = secondDate.get(weekFields.weekBasedYear());
// return if they are equal or not
return firstDatesCalendarWeek == secondDatesCalendarWeek
&& firstWeekBasedYear == secondWeekBasedYear;
}

How to delete SharedPreferences automatically after one month?

I want to delete SharedPreferences, if they exist, after one month automatically. I could not find any solutions. Is this possible to make?
Thanks a lot.
It depends.
The easiest way is to delete it when the user starts the app.
When the apps is created, you check the SharedPreferences for the last updated time.
If it's null (the first time), you save the current time in milliseconds as a long.
If it's not null, you read it and compare it against the current time. If it less than a month, you do nothing. If it's more than a month, you clear the shared preferences and, after clearing it, insert the new time.
Something like:
long lastUpdate = sharedPreferences.getLong(LAST_UPDATE, -1);
if(lastUpdate == -1) {
//First time
sharedPreferences.edit().putLong(LAST_UPDATE, System.currentTimeMillis()).apply();
} else {
boolean isMoreThanAMonth = //Here you should do the math. it depends, you want to consider a month like 30 days, or you want to know if it was in another month... somehthing like that
if(isMoreThanAMonth) {
sharedPreferences.edit().clear().apply()
}
}
Of course, if you want to clear the SharedPreferences even if the user does not open the app you should use a Service. It's more complex and expensive for the OS, so you should try to go for the first one if it fits your requirement.
long installed = context
.getPackageManager()
.getPackageInfo(context.getPackag‌​eName(), 0)
.firstInstallTime
;
public long firstInstallTime
The time at which the app was first installed. Units are as per System.currentTimeMillis().
Now you can compare two date and get months diffrent by using GregorianCalendar
after you get one month different do as you want..clear sharedPrefrence.edit().clear().commit()
One possible way,
1. get the calendar instance.
2. Get maximum day of month.
3. Store in a var1 string in format of dd/mm/yyyy.
4. Get the current date from some calendar object and store in same way from point 3 but in var2.
5. Compare two strings.
6. If match then it will be last day of month and call delete() on your files.
Done.

How to add time to another time - Android

I have timer for a task. And all the sessions will be added up to each other.
Let's say today user spent 5 minutes
Other day he spent 1 hour, here this one hour will be added to the 5 minutes
and so on..
So it will be the total time in one value..
How can I do this ? Is it by Milliseconds or Date object ?
Date is more useful when you are dealing with actual calendar dates.
If you just want to keep track of time intervals/durations, just have a long variable and keep on adding the durations to this.
EDIT : Long.MAX_VALUE is 9,223,372,036,854,775,807. So, you don't really need to worry about the overflow either.
You can keep track of all the milliseconds using Date().getTime(), which returns the time since Epoch. So whenever you need to add/remove, just take your Date object, invoke .getTime(), and add/remove from the total. Then when you're done, you can convert the milliseconds to whatever format you need.

MomentJS like functionality for Android Apps

I have a record with date and time, and I would want to convert the transaction date from current date, differentiate and show number of days.
For e.g.
If the the record has got a date time, which is 1 hours before than Now, the system should show an hour ago...
Similarly if there is a record with 3 days before then instead of showing a date, I would want to show "3 days ago".
No need to use any custom solution.
You can use android.text.format.DateUtils.getRelativeTimeSpanString
It returns a string describing 'time' as a time relative to 'now'.
reference: http://developer.android.com/reference/android/text/format/DateUtils.html

How to strip away a certain case in a SQLite query

I am having problems figuring this out. This is my query:
SELECT * FROM events WHERE date('2012-9-4') >= start_date AND
date('2012-9-4') <= end_date
Now as you can see from above, I am only getting the rows that match that day in some way. In my case, any events that are on that day or came from previous days. The problem is, the case where, say, the previous day has an event from 10:00PM to 12:00AM (2012-9-3), shows up on the next day (2012-9-4). So I need to keep the case like that from happening.
This is where I am having trouble. I have no idea how to get it done correctly. I have tried different things, but they all fail. I need a way to make a statement in the where clause only run when the end date > start date, the end date == current day, and the end time == 00:00. Any advice would be greatly apprecited!!
Don't you just need to turn around the first parts of the where clauses
Where start_date >= date ('2012-9-4') and end_date <= date('2012-9-4')
Assuming your data always has end_date later than start_date (if not, then adding an OR with the reverse to pick them up to).
If, (confused here from the Q) you actually want intersecting dates (overlaps), then you need two intersecting clauses:
where (start_date >= date('2012-09-03 00:00:00') and start_date < date('2012-09-04 00:00:00')) or (end_date >= date('2012-09-03 00:00:00') and end_date < date('2012-09-04 00:00:00'))
I finally figured it out (pretty sure)!
SELECT * FROM events WHERE date('2012-9-4') >= start_date AND
date('2012-9-5') <= end_date AND datetime(end_date,end_time) != datetime(2012-9-5,'00:00')
After 2 days of thinking, I have no idea why using the time as well never occurred to me. I guess I need more practice with databases. In any case, the part I added filters the events listed by date and time. Example would be like my query dates, lets say 11:00PM the 4th to 12:00AM the 5th. The AND datetime(end_date,end_time) != datetime(2012-9-5,'00:00') essentially says "only output when its not the end date with a time of midnight." It will only filter out the 5th and not the 4th because midnight is technically another day. Thats the only case I ever want to filter out events anymore than just between the event periods. I appreciate Wolf5370 for the hints which helped.

Categories

Resources