Cannot automatically add event to Google Calendar - java

I have a problem with my TotalCalendar class. In this class I'm adding every events ( for example: 20 events ) to my own calendar. I should add this events to Google Calendar, but stil it's adding to device calendar. How can I change it? When I put single event to calendar, I can choose kind of calendar, but in this situation, I can't.
public class TotalCalendar {
Context mContext;
Intent mIntent;
public TotalCalendar(Context context) {
this.mContext = context;
}
public boolean insert(String dzien, String miesiac, String lokacja, String tytul, String opis, String godziny) {
int year = Calendar.getInstance().get(Calendar.YEAR);
Calendar beginTime = Calendar.getInstance();
Calendar endTime = Calendar.getInstance();
int currentMonth = Calendar.getInstance().get(Calendar.MONTH);
if((Miesiac(miesiac) == 0) && (currentMonth == 11) )
{
year++;
}
int hh1 = 0;
int mm1 = 0;
int hh2 = 0;
int mm2 = 0;
if(isNumeric(getHH1(godziny)) && isNumeric(getMM2(godziny)))
{
Log.d("debug","numeric");
hh1 = Integer.valueOf(getHH1(godziny)).intValue();
mm1 = Integer.valueOf(getMM1(godziny)).intValue();
hh2 = Integer.valueOf(getHH2(godziny)).intValue();
mm2 = Integer.valueOf(getMM2(godziny)).intValue();
}
else
{
hh1 = 0;
mm1 = 0;
hh2 = 0;
mm2 = 0;
}
beginTime.set(year, Miesiac(miesiac), Integer.valueOf(dzien).intValue(), hh1, mm1);
endTime.set(year, Miesiac(miesiac), Integer.valueOf(dzien).intValue(), hh2, mm2);
Log.d("debug", "Begin time: " + Miesiac(miesiac) + " " + Integer.valueOf(dzien));
long startMillis = beginTime.getTimeInMillis();
long endMillis = endTime.getTimeInMillis();
ContentResolver cr = mContext.getContentResolver();
ContentValues values = new ContentValues();
TimeZone tz = TimeZone.getDefault();
values.put(CalendarContract.Events.DTSTART, startMillis);
values.put(CalendarContract.Events.DTEND, endMillis);
values.put(CalendarContract.Events.TITLE,tytul);
values.put(CalendarContract.Events.DESCRIPTION,opis);
values.put(CalendarContract.Events.CALENDAR_ID,1);
values.put(CalendarContract.Events.EVENT_TIMEZONE,tz.getID());
Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI,values);
Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon();
builder.appendPath("time");
ContentUris.appendId(builder, startMillis);
this.mIntent = new Intent(Intent.ACTION_VIEW).setData(builder.build());
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(mIntent);
return true;
}

Related

How to get all events from SQlite database in Alamkanak Android-Week-View library ? (i keep getting single Event)?

I am trying to add events dynamically from the my SQLite database , but i get a single event in my Week-view which it is the last event i add in the database , i am using Alamkanak Week-View , i stuck with problem and try many ways , please help guys .
mWeekView.setMonthChangeListener(new MonthLoader.MonthChangeListener() {
#Override
public List<? extends WeekViewEvent> onMonthChange(int newYear, int newMonth) {
ArrayList<WeekViewEvent> lastevents = new ArrayList<WeekViewEvent>();
lastevents = loadDateFromJson(newYear,newMonth);
events.addAll(loadDateFromJson(newYear,newMonth));
return events;
}
} );
}
public ArrayList<WeekViewEvent> getmNewEvents(int year , int month ) {
// Parse time.
SimpleDateFormat sdf = new SimpleDateFormat("HH:MM");
Date start = new Date();
Date end = new Date();
start = getMyTime();
try {
end = sdf.parse(new Event().getEndTime());
} catch (ParseException e) {
e.printStackTrace();
}
Calendar now = Calendar.getInstance();
Calendar startTime = (Calendar) now.clone();
startTime.setTimeInMillis(start.getTime());
startTime.set(Calendar.YEAR, now.get(Calendar.YEAR));
startTime.set(Calendar.MONTH, now.get(Calendar.MONTH));
startTime.set(Calendar.DAY_OF_MONTH, getMyDate());
Calendar endTime = (Calendar) startTime.clone();
endTime.add(Calendar.HOUR_OF_DAY, 3);
// Create an week view event.
ArrayList<WeekViewEvent> ThisMonthsEvents = new ArrayList<WeekViewEvent>();
WeekViewEvent weekViewEvent =new WeekViewEvent(1,"Raouf",startTime,endTime);
mNewEvents.add(weekViewEvent);
for (int i = 0; i < mNewEvents.size(); i++) {
mNewEvents.get(i).getStartTime().get(Calendar.MONTH);
if((mNewEvents.get(i).getStartTime().get(Calendar.MONTH) == month)&&(mNewEvents.get(i).getStartTime().get(Calendar.YEAR) == year))
ThisMonthsEvents.add(mNewEvents.get(i));
}
ArrayList<WeekViewEvent> matchedEvents = new ArrayList<WeekViewEvent>();
for (WeekViewEvent event : mNewEvents) {
if (eventMatches(event, year, month)) {
matchedEvents.add(event);
}
}
mWeekView.notifyDatasetChanged();
return ThisMonthsEvents;
}
// here how i am getting dates from my SQlite Database
public int getMyDate() {
DBconexion db = new DBconexion(this);
SQLiteDatabase db2 = db.getReadableDatabase();
Cursor cur = db2.rawQuery("SELECT * FROM " + Table_name, null);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-mm-yyyy");
// looping through all rows and adding to list
String date = null;
Date Date = new Date();
ArrayList<String> dateStringList = new ArrayList<String>();
ArrayList<Date> dateList = new ArrayList<Date>();
int DayOfMonth = 0;
while (cur.moveToNext()) {
dateStringList.add(cur.getString(9));
}
for (String dateString : dateStringList) {
try {
dateList.add(simpleDateFormat.parse(dateString));
} catch (ParseException e) {
e.printStackTrace();
}
}
for (Date datee : dateList) {
DayOfMonth = datee.getDate();
}
return DayOfMonth;
}
i find how to solve this , i use JSONArrays and it works perfectly
here is the code maybe someone will need it!
public List<WeekViewEvent> loadDateFromJson(int year , int month) {
DBconexion dBconexion = new DBconexion(this);
#SuppressLint("SimpleDateFormat") SimpleDateFormat sdfD = new SimpleDateFormat("yy-MM-dd");
#SuppressLint("SimpleDateFormat") SimpleDateFormat sdfT = new SimpleDateFormat("HH:mm");
try {
JSONObject jo = dBconexion.getDateTime();
JSONArray Datejason = jo.getJSONArray("Date");
JSONArray Timejason = jo.getJSONArray("Time");
JSONArray endTimejason = jo.getJSONArray("End Time");
JSONArray Namejason = jo.getJSONArray("Name");
for (int i = 0; i < Datejason.length(); i++) {
//set date
String sd = (String) Datejason.get(i);
Date dfj = sdfD.parse(sd);
int Day = dfj.getDate();
int Month = dfj.getMonth() - 0;
int Year = dfj.getYear();
//set time
String st = (String) Timejason.get(i);
Date tfj = sdfT.parse(st);
int Hour = tfj.getHours();
int Minute = tfj.getMinutes();
String endTimeP = (String) endTimejason.getString(i);
int endTimePeriod = Integer.valueOf(endTimeP);
//set name
String Name = (String) Namejason.getString(i);
//Rand Colors for Events
Random rand = new Random();
int r = rand.nextInt(255);
int g = rand.nextInt(255);
int b = rand.nextInt(255);
int randomColor = Color.rgb(r,g,b);
if(Color.rgb(r,g,b) == getResources().getColor(R.color.white)){
randomColor = getResources().getColor(R.color.red);
}
//Set StarTime
Calendar startTime = Calendar.getInstance();
startTime.set(Calendar.HOUR_OF_DAY, Hour);
startTime.set(Calendar.MINUTE, Minute);
startTime.set(Calendar.YEAR, year);
startTime.set(Calendar.MONTH, Month);
startTime.set(Calendar.DAY_OF_MONTH, Day);
Calendar endTime = (Calendar) startTime.clone();
endTime.add(Calendar.HOUR_OF_DAY, endTimePeriod);
WeekViewEvent weekViewEvent = new WeekViewEvent(1, Name, startTime, endTime);
weekViewEvent.setColor(randomColor);
myEvent.add(weekViewEvent);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return myEvent;
}
onMonthChange will look like
mWeekView.setMonthChangeListener(new MonthLoader.MonthChangeListener() {
#Override
public List<? extends WeekViewEvent> onMonthChange(int newYear, int newMonth) {
List<WeekViewEvent> lastone = new ArrayList<WeekViewEvent> ();
lastone = loadDateFromJson( newYear , newMonth);
events.addAll(lastone);
ArrayList<WeekViewEvent> matchedEvents = new ArrayList<WeekViewEvent>();
for (WeekViewEvent event : events) {
if (eventMatches(event, newYear, newMonth)) {
matchedEvents.add(event);
}
}
return matchedEvents;
}
} );
}

Android weekly event not being set for all the days

I have searched extensively on SO and various forums and I can't figure this one out. I'm generating a reccuring event in Android calendar. Sometimes it works flawlessly and sometimes it sets it only for the upcoming 4-5 weeks and then stops. What precisely am I doing wrong here?
This is my function that adds an event in the calendar
private void addToCalendar(int DAY_WEEK, String TITLE, String DESC, String LOC, int hour_s, int min_s, int hour_e, int min_e) {
Uri uri = Calendars.CONTENT_URI;
String[] projection = new String[]{
Calendars._ID,
Calendars.ACCOUNT_NAME,
Calendars.CALENDAR_DISPLAY_NAME,
Calendars.NAME,
Calendars.CALENDAR_COLOR
};
// Construct event details
long startMillis = 0;
long endMillis = 0;
int year = Calendar.getInstance().get(Calendar.YEAR);
int month = Calendar.getInstance().get(Calendar.MONTH);
Calendar now = Calendar.getInstance();
int day = now.get(Calendar.DAY_OF_WEEK);
int daym = now.get(Calendar.DAY_OF_MONTH);
int start_day = 0;
if (day != DAY_WEEK) {
start_day = daym - (day - DAY_WEEK);
//Toast.makeText(this, Integer.toString(start_day), Toast.LENGTH_LONG).show();
} else {
start_day = daym;
}
Calendar beginTime = Calendar.getInstance();
beginTime.set(year, month, start_day, hour_s, min_s);
startMillis = beginTime.getTimeInMillis();
Calendar endTime = Calendar.getInstance();
endTime.set(year, month, start_day, hour_e, min_e);
endMillis = endTime.getTimeInMillis();
Calendar endRRule = Calendar.getInstance();
endRRule.add(Calendar.MONTH, 3);
long endRRuleMillis = endRRule.getTimeInMillis();
// Insert Event
ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues();
TimeZone timeZone = TimeZone.getDefault();
values.put(Events.DTSTART, startMillis);
values.put(Events.DTEND, endMillis);
values.put(Events.EVENT_TIMEZONE, timeZone.getID());
values.put(Events.RRULE, "FREQ=WEEKLY;");
values.put(Events.HAS_ALARM, 1);
values.put(Events.TITLE, TITLE);
values.put(Events.DESCRIPTION, DESC);
values.put(Events.EVENT_LOCATION, LOC);
values.put(Events.CALENDAR_ID, 1);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_CALENDAR}, 101);
}
uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
// Retrieve ID for new event
String eventID = uri.getLastPathSegment();
ContentValues reminders = new ContentValues();
reminders.put(CalendarContract.Reminders.EVENT_ID, eventID);
reminders.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);
reminders.put(CalendarContract.Reminders.MINUTES, 15);
Uri uri2 = cr.insert(CalendarContract.Reminders.CONTENT_URI, reminders);
}
And I am calling it from another function which I shortened in order to improve code readability
This loop goes through all of the SQL results from the local database
while (c.moveToNext()) {
Log.d("COURSE NAME", c.getString(c.getColumnIndex("course_name")));
final ListModelSchedules sched = new ListModelSchedules();
...
if (setDay != 0 && title != null && desc != null && room != null && setStartTime != 0 && setEndTime != 0)
{
addToCalendar(setDay, title, desc, room, setStartTime, 0, setEndTime, 0);
}
}
It adds the event correctly, but instead of it being repeaten indefinitely, it sometimes stops after 4-5 weeks. What am I doing wrong here? If I set RRule's UNTIL=timestamp, it breaks and adds nothing to the calendar. Any help would be appreciated.
EDIT: I just noticed that it actually adds all those events for all of the days. But it shows after you manually select a refresh option inside the calendar app. Is this something that can be solved or is it just the way calendar app is designed?

Flipping images from PM to AM time

I am having set of 8 images. Here the images will be flipping according to the time which is set by the user and their will be default wake up time 7:00am. If the user sets the time at 10:10pm and the wake up time is 7:00am. Now, the images needs to flip and the flipping of images are in percentage wise i.e; 0% 20% 40% 60% 80% 90% 95% 100% of the total time. Now, the images are flipping when i am setting the time from 10:00am to 7:00pm , 9:00am to 11:00am , 7:00pm to 8:30pm etc. But when i am setting from 10:00pm to 7:00am the images are not flipping.
c = Calendar.getInstance();
SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
SimpleDateFormat testhrFormat = new SimpleDateFormat("HH");
SimpleDateFormat testminFormat = new SimpleDateFormat("mm");
String formattedDate = testhrFormat.format(c.getTime());
int minDate = Integer.parseInt(testminFormat.format(c.getTime()));
long hrlong = TimeUnit.HOURS.toMinutes(Long.parseLong(formattedDate));
addedmin = hrlong + minDate;
twwntyhrformat = displayFormat.format(c.getTime());
SimpleDateFormat parseFormat = new SimpleDateFormat("HH:mm a");
SharedPreferences timegot = getSharedPreferences("CHILDTIME", MODE_PRIVATE);
String time = timegot.getString("savedwakeuptime", "");
try {
Date date = parseFormat.parse(time);
String gottime = displayFormat.format(date);
String[] timedivided = gottime.split(":");
String gothr = timedivided[0];
long gotlong = TimeUnit.HOURS.toMinutes(Long.parseLong(gothr));
String gotmin = timedivided[1];
int gotintmin = Integer.parseInt(gotmin);
addgottime = gotlong + gotintmin;
long subtime = addgottime - addedmin;
String submilli = String.valueOf(subtime);
long submillitimeunit = TimeUnit.MINUTES.toMillis(Long.parseLong(submilli));
final int gotflippingtime = (int) submillitimeunit;
handler = new Handler();
run = new Runnable() {
#Override
public void run() {
String number = String.valueOf(fliper.getDisplayedChild());
if (number.equals("7")) {
handler.removeCallbacks(run);
back_home.setEnabled(true);
} else {
fliper.showNext();
handler.postDelayed(run, gotflippingtime);
}
}
};
for (int gotinterval : gotintervals) {
handler.postDelayed(run, gotinterval);
}
handler.postDelayed(run, gotflippingtime);
} catch (ParseException e) {
e.printStackTrace();
}
} else {
c = Calendar.getInstance();
SimpleDateFormat testhrFormat = new SimpleDateFormat("HH");
SimpleDateFormat testminFormat = new SimpleDateFormat("mm");
String formattedDate = testhrFormat.format(c.getTime());
int minDate = Integer.parseInt(testminFormat.format(c.getTime()));
long hrlong = TimeUnit.HOURS.toMinutes(Long.parseLong(formattedDate));
addedmin = hrlong + minDate;
SharedPreferences timegot = getSharedPreferences("CHILDTIME", MODE_PRIVATE);
long numberlong = timegot.getLong("savedwakeuptime",0);
long millicurrenttime=TimeUnit.MINUTES.toMillis(addedmin);
long subtime = numberlong-millicurrenttime;
Log.d("Calc", String.valueOf(subtime)+" "+String.valueOf(numberlong)+" "+String.valueOf(millicurrenttime));
flippingtime = (int) subtime;
intervals = new ArrayList<Integer>();
intervals.add((int) (flippingtime * 0.20f));
intervals.add((int) (flippingtime * 0.40f));
intervals.add((int) (flippingtime * 0.60f));
intervals.add((int) (flippingtime * 0.80f));
intervals.add((int) (flippingtime * 0.90f));
intervals.add((int) (flippingtime * 0.95f));
intervals.add((int) (flippingtime * 1.00f));
intervals.add(flippingtime);
handler = new Handler();
run = new Runnable() {
#Override
public void run() {
String number = String.valueOf(fliper.getDisplayedChild());
if (number.equals("7")) {
handler.removeCallbacks(run);
} else {
fliper.showNext();
handler.postDelayed(run, flippingtime);
}
}
};
for (int interval : intervals) {
handler.postDelayed(run, interval);
}
handler.postDelayed(run, flippingtime);

Pop Up notifications on a daily/weekly/monthly basis depending on the selected date

Here the user is able to pick a date(goal date) using datepicker. The date gets saved in the database. Then the notification pops up on the screen only if the due date is within 2 days. I wanted to figure out how to show the notification on a daily / weekly / monthly basis depending on the date selected. I checked different sites but didnt get a proper solution. Please help!
MainActivity
swipelist.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
// ApplicationInfo item = mAppList.get(position);
final MyImage image = (MyImage) swipelist.getItemAtPosition((int) position);
switch (index) {
case 0:
// open
LayoutInflater li = LayoutInflater.from(MainActivity.this);
View DateView = li.inflate(R.layout.calendar_cam, null);
build = new AlertDialog.Builder(MainActivity.this);
build.setTitle("Reminder");
build.setMessage("Pick a date");
build.setView(DateView);
newDate = (Button) DateView.findViewById(R.id.buttonCalCam); //Button which opens the calender
newDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
final Calendar c = Calendar.getInstance();
currentYear = c.get(Calendar.YEAR);
currentMonth = c.get(Calendar.MONTH);
currentDay = c.get(Calendar.DAY_OF_MONTH);
build.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
database = dbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(DBhelper.COLUMN_DESCRIPTION, dateString);
Log.d("Updating Date: ", ".....");
String whereClause =
DBhelper.COLUMN_TITLE + "=? AND " + DBhelper.COLUMN_DATETIME + "=?";
String[] whereArgs = new String[]{image.getTitle(), String.valueOf(image.getDatetimeLong())};
database.update(DBhelper.TABLE_NAME, cv, whereClause, whereArgs);
Log.d("Updating Date: ", ".....");
image.setDescription(dateString);
swipelist.invalidateViews();
//Scheduling Notifications
int curYear = c.get(Calendar.YEAR), curMonth = c.get(Calendar.MONTH) + 1, curDay = c.get(Calendar.DAY_OF_MONTH);
int goalYear = Integer.parseInt(yearG), goalMonth = Integer.parseInt(monthG), goalDay = Integer.parseInt(dayG);
int calYear = 0, calMonth = 0, calDay = 0, calDayGoal = 0;
//Get current date
String curDate = String.valueOf(curDay) + "/" + String.valueOf(curMonth) + "/" + String.valueOf(curYear);
//Get goal date
String goalDate = String.valueOf(goalDay) + "/" + String.valueOf(goalMonth) + "/" + String.valueOf(goalYear);
int count = -1;
//Fetches the date and Time from system, hence not used
if (curYear < goalYear || (goalYear == curYear && goalMonth > curMonth) || (goalYear == curYear && goalMonth == curMonth && goalDay > curDay)) {
count = 0;
int i;
for (i = curYear; i < goalYear; i++) {
if (i % 4 == 0) {
count += 366;//Leap year
} else {
count += 365;// Non leap year
}
}
//calculating the no of days left from current date to goal date
count -= calMonthDay(curMonth, curYear);
count -= curDay;
count += calMonthDay(goalMonth, goalYear);
count += goalDay;
if (count < 0) {
count *= -1;
}
if (count != 1) {
daysLeftGoal.add(String.valueOf(count) + " days left");
Toast.makeText(getBaseContext(), "Days Left: "+count, Toast.LENGTH_LONG).show();
}else
daysLeftGoal.add(String.valueOf(count) + " day left");
} else {// current year exceeds goal year
daysLeftGoal.add("Times up");
}
mContext=getApplicationContext();
// check if goal date is less than or equals 2 days
if (count <= 2 && count >= 0) {
Intent resultIntent = new Intent(mContext, MainActivity.class);
//resultIntent.putExtra("ID", mCursor.getString(mCursor.getColumnIndex(DbHelperGoal.KEY_ID)));
resultIntent.putExtra("update", true);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//TaskStackBuilder requires API 16 [4.1] min
if (Build.VERSION.SDK_INT > 15) {
TaskStackBuilder stackBuilder = TaskStackBuilder.create(MainActivity.this);
//stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
} else {
resultPendingIntent = PendingIntent.getActivity(MainActivity.this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//deletePendingIntent = PendingIntent.getActivity(MainActivity.this, 0, deleteIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
gBuilder = new NotificationCompat.Builder(MainActivity.this).setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My Goals")
.setContentText("Reminder Set: " + image.getDescription())
.addAction(R.drawable.ic_action_about, "View", resultPendingIntent);
//.addAction(R.drawable.ic_action_discard, "Delete", deletePendingIntent);
gBuilder.setContentIntent(resultPendingIntent);
//gBuilder.setContentIntent(deletePendingIntent);
gBuilder.setPriority(2);// [-2,2]->[PRIORITY_MIN,PRIORITY_MAX]
//for the sound and float notification
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 14);//set the alarm time
calendar.set(Calendar.MINUTE, 57);
calendar.set(Calendar.SECOND, 0);
gBuilder.setWhen(System.currentTimeMillis())
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000}).setLights(Color.WHITE, 0, 1);
//gBuilder.setWhen(calendar.getTimeInMillis()).setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE).setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)).setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }).setLights(Color.WHITE, 0, 1);
// opens the resultPendingIntent
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
// open the activity every 24 hours
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24 * 60 * 60 * 1000, resultPendingIntent);
gBuilder.setAutoCancel(true);
//int mNotificationId = mCursor.getInt(mCursor.getColumnIndex(DbHelperGoal.KEY_ID));
//keyIndex = mCursor.getInt(mCursor.getColumnIndex(DbHelperGoal.KEY_ID));
int mNotificationId=position;
// Gets an instance of the NotificationManager service
myGoalNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
myGoalNotifyMgr.notify(mNotificationId, gBuilder.build());
}
}
});
alert=build.create();
alert.show();
break;
// calculates days from months
int calMonthDay(int m,int y){//calMonthDay(month,year)
int x=0,c;
for(c = 1; c < m; c++) {// Jan to less than the month 'm' as 'm' we are not taking the the whole days of that month
if(c == 2) {//if Feb
if(y%4 == 0)//checks if year is leap or not
x += 29;
else
x += 28;
}
else
x += mon.get(c-1);
}
return(x);
}
//calculates no. of months from current month & year to goal month & year
int calDateMonth(int mC,int yC,int mG,int yG){//(current-month, current-year, goal-month, goal-year)
int x = 0,i,countM=0;
if(yC<=yG){
for(i = yC; i < yG; i++)
countM += 12;
}
countM -= mC;
countM += mG;
return (countM);
}
//calculates no. of weeks from current month & year to goal month & year
int calDateWeek(int mC,int yC,int mG,int yG){
int x = 0,i,countW=0;
if(yC<=yG){
for(i = yC; i < yG; i++)
countW+=52;
}
countW -= mC;
countW += mG;
countW *= 4;
return (countW);
}
DatePicker
private DatePickerDialog.OnDateSetListener reservationDate = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day){
final Calendar c = Calendar.getInstance();
Date convertedDate = new Date();
int curYear = c.get(Calendar.YEAR), curMonth = c.get(Calendar.MONTH)+1, curDay = c.get(Calendar.DAY_OF_MONTH);
//Picks the selected date, month & year & displays on button
if((year>curYear)||(year==curYear && month+1>curMonth)||(year==curYear && month+1==curMonth && day>curDay)) {
dayG = Integer.toString(day);
monthG = Integer.toString(month + 1);
yearG = Integer.toString(year);
Log.d("Setting Date: ", ".....");
dateString=String.valueOf(dayG)+"-"+String.valueOf(monthG)+"-"+String.valueOf(yearG);
Toast.makeText(getBaseContext(), "Your reminder is set to " + day + "-" + (month + 1) + "-" + year + ".", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getBaseContext(), "Please choose date after " + curDay + "-" + curMonth + "-" + curYear, Toast.LENGTH_SHORT).show();
}
}
};

Check if time is inbetween timerange in Android

I am trying to check if the current time is in the range of a specified range. I made a method to check this, but it doesn't work. I'm not sure why not and how to get it to work.
private Calendar fromTime;
private Calendar toTime;
private Calendar currentTime;
public boolean checkTime(String time) {
try {
String[] times = time.split("-");
String[] from = times[0].split(":");
String[] until = times[1].split(":");
fromTime = Calendar.getInstance();
fromTime.set(Calendar.HOUR, Integer.valueOf(from[0]));
fromTime.set(Calendar.MINUTE, Integer.valueOf(from[1]));
toTime= Calendar.getInstance();
toTime.set(Calendar.HOUR, Integer.valueOf(until[0]));
toTime.set(Calendar.MINUTE, Integer.valueOf(until[1]));
currentTime = Calendar.getInstance();
currentTime.set(Calendar.HOUR, Calendar.HOUR_OF_DAY);
currentTime.set(Calendar.MINUTE, Calendar.MINUTE);
if(currentTime.after(fromTime) && currentTime.before(toTime)){
return true;
}
} catch (Exception e) {
return false;
}
return false;
}
I am trying to test it like this:
if(checkTime("06:00-19:00")){
inRange = true;
}
The NPE is gone, but it's still not calculating if the time is in the range of fromTime to toTime. Any help is very much appreciated!
Initialize variables and change the return type of your method to boolean.
private Calendar fromTime;
private Calendar toTime;
private Calendar currentTime;
public boolean checkTime(String time) {
try {
String[] times = time.split("-");
String[] from = times[0].split(":");
String[] until = times[1].split(":");
fromTime = Calendar.getInstance();
fromTime.set(Calendar.HOUR_OF_DAY, Integer.valueOf(from[0]));
fromTime.set(Calendar.MINUTE, Integer.valueOf(from[1]));
toTime = Calendar.getInstance();
toTime.set(Calendar.HOUR_OF_DAY, Integer.valueOf(until[0]));
toTime.set(Calendar.MINUTE, Integer.valueOf(until[1]));
currentTime = Calendar.getInstance();
currentTime.set(Calendar.HOUR_OF_DAY, Calendar.HOUR_OF_DAY);
currentTime.set(Calendar.MINUTE, Calendar.MINUTE);
if(currentTime.after(fromTime) && currentTime.before(toTime)){
return true;
}
} catch (Exception e) {
return false;
}
return false;
}
You have not initialized toTime and fromTime objects before using them. So better call toTime = Calendar.getInstance(); before.
private Calendar fromTime;
private Calendar toTime;
private Calendar currentTime;
public boolean checkTime(String time) {
try {
String[] times = time.split("-");
String[] from = times[0].split(":");
String[] until = times[1].split(":");
fromTime = Calendar.getInstance();
fromTime.set(Calendar.HOUR, Integer.valueOf(from[0]));
fromTime.set(Calendar.MINUTE, Integer.valueOf(from[1]));
toTime = Calendar.getInstance();
toTime.set(Calendar.HOUR, Integer.valueOf(until[0]));
toTime.set(Calendar.MINUTE, Integer.valueOf(until[1]));
currentTime = Calendar.getInstance();
currentTime.set(Calendar.HOUR, Calendar.HOUR_OF_DAY);
currentTime.set(Calendar.MINUTE, Calendar.MINUTE);
if(currentTime.after(fromTime) && currentTime.before(toTime)){
return true;
}
} catch (Exception e) {
return false;
}
return false;
}
this
currentTime.set(Calendar.HOUR, Calendar.HOUR_OF_DAY);
currentTime.set(Calendar.MINUTE, Calendar.MINUTE);
Doesn't do what you would like it to do. What it does is set the field HOUR to the value of Calendar.HOUR, which is an arbitrary constant.
You don't need those 2 lines as getInstance returns a Calendar at the current time.
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
//cal.add(Calendar.DATE, 1);
String date = sdf.format(cal.getTime());
String dateStart = date+" "+"11:30:00";
String date2 = sdf.format(cal2.getTime());
String dateStop = date2+" "+"23:00:00";
Calendar calendar = Calendar.getInstance();
String currentTime = format.format(calendar.getTime());
Date d1 = null;
Date d2 = null;
Date d3 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
d3 = format.parse(currentTime);
// Toast.makeText(getApplicationContext(),""+dateCal,Toast.LENGTH_SHORT).show();
if (d3.before(d2)
&& d3.after(d1) ){}else{} } catch (ParseException e) {
e.printStackTrace();
}
Put currentTime outside of setTime and remove if-statement from setTime.
If you need put if-statement outside of setTime.
private boolean checkBedTime(String time) {
// Time Pattern Like : "06:00-19:00"
String[] times = time.split("-");
String[] from = times[0].split(":");
String[] until = times[1].split(":");
int fromHour = Integer.parseInt(from[0]);
int fromMinute = Integer.parseInt(from[1]);
int toHour = Integer.parseInt(until[0]);
int toMinute = Integer.parseInt(until[1]);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
int currentMinute = calendar.get(Calendar.MINUTE);
int convertedFromMinute = (fromHour * 60) + fromMinute;
int convertedToMinute = (toHour * 60) + toMinute;
int convertedCurrentMinute = (currentHour * 60) + currentMinute;
if (convertedFromMinute == convertedToMinute) {
Toast.makeText(context, "Sleep Time & Wake Up Time can't be same", Toast.LENGTH_SHORT).show();
return false;
} else if (convertedToMinute < convertedFromMinute) {
convertedToMinute = convertedToMinute + (24 * 60);
}
Log.v("Time", "FromMinute --> " + convertedFromMinute);
Log.v("Time", "ToMinute --> " + convertedToMinute);
Log.v("Time", "CurrentMinute -- > " + convertedCurrentMinute);
if (convertedCurrentMinute >= convertedFromMinute && convertedCurrentMinute <= convertedToMinute) {
return true;
} else {
return false;
}
}

Categories