Setting an alarm based on date in database - java

I found a tutorial that helped me get a working alarm setup but in the tutorial we used a date picker to set the time of the alarm. All was going well, so I attempted to replace the date picker with a method of my own and set the alarm that way. Problem is it doesn't seem to be working, no alarm pops up when I set that date to today but works fine when I use the date picker. Can anyone tell me what I'm doing wrong? I ran this through debug and my query is returning the proper date, I'm getting the right numbers and all but it doesn't seem to work.
I'm hoping someone can point out something I've missed?
EDIT
I call setNotif() through a button in the ui. I basically remodelled it to just have a button for testing. I get the toast but no alarm goes off no matter what I try.
Here's the original date picker code
public void onDateSelectedButtonClick(View v){
int day = picker.getDayOfMonth();
int month = picker.getMonth();
int year = picker.getYear();
Calendar c = Calendar.getInstance();
c.set(year, month, day);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
scheduleClient.setAlarmForNotification(c);
Toast.makeText(this, "Notification set for: "+ day +"/"+ (month+1) +"/"+ year, Toast.LENGTH_SHORT).show();
}
Here's the method I tried to replace it with
It calls a query to get a specific date from my database and supposedly sets an alarm 3 days prior. I tested it by changing the date of my phone and by making it set the alarm to today as well but neither have worked.
public void setNotif() {
// Getting the next date of payments which the alarm will be based on
DatabaseHelper db = new DatabaseHelper(this);
String thisdate = getCurDate();
Cursor cur = db.nextdate(thisdate);
String date= "";
if (cur!= null) {
if (cur.moveToFirst()) {
date = cur.getString(0);
}
}
try {
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
Date input = inputFormat.parse(date);
String finaldate = inputFormat.format(input);
String d = finaldate.substring(8,10);
String m = finaldate.substring(5,7);
String y = finaldate.substring(0,4);
int da = Integer.parseInt(d);
int month = Integer.parseInt(m);
int year = Integer.parseInt(y);
int day = da - 3;
Calendar c = Calendar.getInstance();
c.set(year, month, day);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
scheduleClient.setAlarmForNotification(c);
Toast.makeText(this, "Notification set for: "+ day +"/"+ month +"/"+ year, Toast.LENGTH_SHORT).show();
}catch (Exception ex) {
Alerts.CatchError(Kik.this, ex.toString());
}
}

This is an easy road block to run into, unfortunately and it doesn't really have anything to do with Android. It's a holdover from Java date/calendar.
When you pull the date out of the int month out of the date picker in the example code the value you get out is 0 based:
int month = picker.getMonth();
// January -> 0
// February -> 1
// ...
// December -> 11
The dates in your database are dates we're used to looking at: 2016-12-25 is December 25th, 2016.
When you set the values for Calendar it is expecting a 0-indexed month. You're giving it a 1-indexed month. So you'll need to subtract 1 from the month to get the right value. I'll make a table so it's clear what's going on:
Month String | Database Value | Calendar Value
January | 1 | 0
February | 2 | 1
March | 3 | 2
April | 4 | 3
May | 5 | 4
June | 6 | 5
Hopefully that makes it obvious.
So in your case if you change the line:
c.set(year, month, day);
To be...
c.set(year, month - 1, day);
You'll win.

Related

Take away a single day using Calendar in Java?

I have an application that plugs into the Google Fit Api and returns the steps for the last 7 days, the method is below. As the screen shot shows though I wish to add the day to the step count.
I have tried many options to take away one day at a time for the 7 loop but had no luck, it just says the same day. Any help would be great thank you.
private void dumpDataSet(DataSet dataSet) {
Log.i(TAG, "Data returned for Data type: " + dataSet.getDataType().getName());
DateFormat dateFormat = DateFormat.getTimeInstance();
int i = 0;
for (DataPoint dp : dataSet.getDataPoints()) {
for(Field field : dp.getDataType().getFields()) { //loop 7 times
int test = dp.getValue(field).asInt();
String weekSteps= String.valueOf(test); //get weekday steps one at a time
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Calendar cal = Calendar.getInstance();
String weekday = sdf.format(cal.getTime());
String weekStepsFinal= weekSteps + " steps on " + weekday; //set Textfield to steps and the day
FeedItem item = new FeedItem();
item.setTitle(weekStepsFinal);
feedItemList.add(item);
}
}
}
There are 7 datasets btw.
If by "take away one day at a time" means that you want the days going backwards, then here's how:
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
System.out.println("Last 7 days (starting today):");
Calendar cal = Calendar.getInstance(); // Initialized to today/now
for (int i = 0; i < 7; i++) {
System.out.println(" " + sdf.format(cal.getTime()));
cal.add(Calendar.DAY_OF_MONTH, -1); // Update to previous day at same time-of-day
}
OUTPUT
Last 7 days (starting today):
Monday
Sunday
Saturday
Friday
Thursday
Wednesday
Tuesday
This will subtract 7 days from the calendar to get you the date 7 days ago:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -7).
To subtract one day use the following code :
int DAY_IN_MILLIS = 1000 * 60 * 60 * 24;
Date currentDate = new Date();
long previousDay = currentDate.getTime()-DAY_IN_MILLIS;
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
String day = sdf.format(previousDay);

Calendar view in android should display 1 week from current date

I am trying to get the CalendarView widget to display only 1 week from current date. I tried using ,
Date date = new Date();
cal = (CalendarView) findViewById(R.id.calendarView1);
cal.setMaxDate(date.getTime()+604800000);
cal.setMinDate(date.getTime());
but it doesn't seem to work. Really appreciate if someone could help me out.
u can set like this here eg. i set the date to 25 -12(december)- current year. You want something like: just get 1 week from current date and u can set like this also
public static Calendar defaultCalendar() {
Calendar currentDate = Calendar.getInstance();
currentDate.set(Calendar.MONTH, 11); // Months are 0-based!
currentDate.set(Calendar.DAY_OF_MONTH, 25); // Clearer than DATE
return currentDate;
}

Calendar day of month Android

I choose the starting date (example 31/01/2014) and ending date (example 31/12/2014), I insert a record every month. If I get the next month is February 28th, but then I always get 28 though March, April, etc. ..
How can I fix? I hope I explained
SimpleDateFormat sdf1 = new SimpleDateFormat( "yyyy-MM-dd" );
ContentValues cv = new ContentValues();
for(
int i=0;
calendar1.getTime().before(calendar2.getTime());
i++
) {
calendar1.add(Calendar.MONTH, 1);
if (calendar1.getTime().before(calendar2.getTime())) {
String strDate = sdf1.format(calendar1.getTime());
cv.put(etableTable.DATE, strDate);
db.insert(etableTable.TABLE_NAME, null, cv);
...
}
}
Assuming that you speak about class GregorianCalendar - Instead of calendar1.add(Calendar.MONTH, 1) try to also call following method as work-around:
static GregorianCalendar moveToEndOfMonth(GregorianCalendar gcal) {
gcal.add(Calendar.MONTH, 1); // moving to some day of next month
gcal.set(Calendar.DAY_OF_MONTH, 1); // moving to first day of current month
gcal.add(Calendar.DATE, -1); // moving to last day of previous month
}
So your final code should look like:
calendar1.add(Calendar.MONTH, 1);
moveToEndOfMonth(calendar1);
Why? The analysis of #DavidCAdams is right, see his answer.
Where are you creating the calendar objects? Since you are incrementing the MONTH, and it is January 30, you get February 28 for the next month, since next month only has 28 days in it. There is no Feb 30, 2014. Thereafter, when you increment the month, you get March 28, April 28, etc. etc.

1970 Datepicker date

I'm trying to set the Date Picker of my app with the retrieved date value stored in my database on the OnCreate method. Everything is fine until I come to set the date picker with the year, month and day values themselves. At the moment the date picker is always being set to '01 Jan 1970'. Hopefully someone can point me int the right direction here.
As shown I parse the string to a Date object then retrieve the separate year, month and day values. They're stored as interger, then using the .init method it should set my date picker.
Here's my code so far:
DBHandlerApp dateToEdit= new DBHandlerApp(this, null, null);
dateToEdit.open();
String returnedDate = dateToEdit.getTime(passedID);
SimpleDateFormat newFormatDate = new SimpleDateFormat("dd-MMM-yyyy");
try
{
dateToEditApp = newFormat.parse(returnedDate);
} catch (ParseException e)
{
e.printStackTrace();
}
Calendar calDate = Calendar.getInstance();
calDate.setTime(dateToEditApp);
int year = calDate.get(Calendar.YEAR);
int monthOfYear = calDate.get(Calendar.MONTH);
int dayOfMonth = calDate.get(Calendar.DAY_OF_MONTH);
editDatePicker.init(year, monthOfYear, dayOfMonth, null);
There might be a small issue with your code, i think you misnamed the newFormatDate when trying to parse it, which would goto the default value of the dateToEditApp (which is the 1-1-1970 date)
shouldnt
dateToEditApp = newFormat.parse(returnedDate);
be
dateToEditApp = newFormatDate.parse(returnedDate);
?
the date '01 Jan 1970' is an default value, because it starts counting milliseconds from '01 Jan 1970' till today. So I guess something went wrong, when you acquire your date from the database or while parsing it. Can you check wether the parse throws an exception?

What is the Android equivalent of iPhone's NSCalendar?

What might be the Android equivalent of the following iPhone code?
NSCalendar *calender = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
int units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *components = [calender components:units fromDate:[NSDate date] toDate:destinationDate options:0];
I am trying to do a date countdown to show the number of years, months, days, hours, minutes and seconds in a consecutive manner, not show the years, months, days, hours, minutes and seconds as a whole.
I have this, but I cannot get the hours, minutes and seconds. When I play with the hours, I keep getting hours in the days, not hours left.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = format.parse(myDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long nat = Math.round(date.getTime() / 1000);
long totaldifference = Math.abs(d1-d2);
long date_diff = Math.round(totaldifference/(24*3600));
//year
double year2 = Math.floor(date_diff/365);
date_diff-=year2*365;
double month2 = Math.floor(date_diff/30.5);
date_diff-=month2*30.5;
long day2 = date_diff;
To get a Calendar, you can do this:
Calendar cal = Calendar.getInstance()
Doing it this way will initialize it to the current date and time. Check the documentation if you need to set it to a different date or time.
To get the year, month, day, and so on, you can do this:
int year = cal.get(Calendar.YEAR)
int month = cal.get(Calendar.MONTH)
int day = cal.get(Calendar.DATE)
To "count down" on that, you can add a negative of whatever unit you want to count down in:
cal.add(Calendar.SECOND, -1)
Have a look at the documentation for calendar it should help. You get the year, month, day etc all seperately so should be easy to implement your countdown. Its a base class so you should be able to extend it to do what you need.

Categories