I am using alam kanak week view in my app. I have an event for which I know the date, the start time and the end time. Now what function to call to add this event to the weekview. Suppose the date I have is 20-10-2015 and time is 17:30 to 18:30.
I am unable to add this event to the view. Please provide if there is anything.
This is how Alam-Kanak is adding an event:
Calendar startTime = Calendar.getInstance();
startTime.set(Calendar.HOUR_OF_DAY, 5);
startTime.set(Calendar.MINUTE, 0);
startTime.set(Calendar.MONTH, newMonth-1);
startTime.set(Calendar.YEAR, newYear);
startTime.add(Calendar.DATE, 1);
Calendar endTime = (Calendar) startTime.clone();
endTime.add(Calendar.HOUR_OF_DAY, 3);
endTime.set(Calendar.MONTH, newMonth - 1);
WeekViewEvent event = new WeekViewEvent(3, "Test title", startTime, endTime);
event.setColor(getResources().getColor(R.color.event_color_03));
CommonItems.events.add(event);
This event shows up.
This is the response I am getting from my server for my custom event:
{ "error": false, "appointments": [
{
"id": "1",
"staff_id": null,
"technician_id": "1",
"name": "Test",
"address": "Vijayanagar",
"pincode": "580040",
"mobile": "9876543210",
"email": "test#gmail.com",
"date": "2015-09-22",
"time": "16:30:00",
"latitude": null,
"longitude": null,
"status": "open",
"created_at": "2015-09-06 18:04:47",
"updated_at": null
} ] }
This is how I am adding my event:
try {
JSONObject jo = new JSONObject(response);
JSONArray ja = jo.getJSONArray("appointments");
for (int i = 0; i < ja.length(); i++) {
JSONObject index = ja.getJSONObject(i);
String name = index.getString("name");
String date = index.getString("date");
String[] dateSplit = date.split("-");
int date_year = Integer.parseInt(dateSplit[0]);
int date_month = Integer.parseInt(dateSplit[1]);
int date_day = Integer.parseInt(dateSplit[2]);
String time = index.getString("time");
String[] timeSplit = time.split(":");
int time_hour = Integer.parseInt(timeSplit[0]);
int time_minute = Integer.parseInt(timeSplit[1]);
Calendar startTime = Calendar.getInstance();
startTime.set(Calendar.HOUR_OF_DAY, 4);
startTime.set(Calendar.MINUTE, time_minute);
startTime.set(Calendar.DATE, date_day);
startTime.set(Calendar.MONTH, date_month);
startTime.set(Calendar.YEAR, date_year);
Calendar endTime = (Calendar) startTime.clone();
endTime.set(Calendar.HOUR_OF_DAY, 4+1);
endTime.set(Calendar.MINUTE, time_minute);
WeekViewEvent event = new WeekViewEvent(1, name, startTime, endTime);
event.setColor(getResources().getColor(R.color.event_color_01));
CommonItems.events.add(event);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This wont show up.! I am unable to understand whats wrong. Please help.
I have done this way by little bit change in library:
Change onSingleTapConfirmed #Override method:
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if (mEventClickListener != null) {
boolean didSelect = false;
if (mEventRects != null) {
List<EventRect> reversedEventRects = mEventRects;
Collections.reverse(reversedEventRects);
for (EventRect event : reversedEventRects) {
if (event.rectF != null && e.getX() > event.rectF.left
&& e.getX() < event.rectF.right
&& e.getY() > event.rectF.top
&& e.getY() < event.rectF.bottom) {
mEventClickListener.onEventClick(
event.originalEvent, event.rectF);
playSoundEffect(SoundEffectConstants.CLICK);
didSelect = true;
break;
}
}
}
if (!didSelect) {
int day_1 = mFirstVisibleDay.get(Calendar.DAY_OF_YEAR);
int day_2 = mLastVisibleDay.get(Calendar.DAY_OF_YEAR);
int chosen_day;
if (day_1 != day_2) {
chosen_day = (int) (day_1 - 1 + Math.round((e.getX() - mHeaderColumnPadding - (mNumberOfVisibleDays-1)*mColumnGap - mTextSize)
/ mWidthPerDay));
} else {
chosen_day = day_1;
}
Calendar RETCAL = Calendar.getInstance();
RETCAL.setTime(mFirstVisibleDay.getTime());
// int totalY = mScroller
int chosen_hour = Math.max(Math.min((int) Math.round((e.getY() - mHeaderTextHeight - mHeaderRowPadding - mHeaderMarginBottom - mScroller
.getCurrY()) / mHourHeight),23),0);
RETCAL.set(Calendar.DAY_OF_YEAR, chosen_day);
RETCAL.set(Calendar.HOUR_OF_DAY, chosen_hour-1);
RETCAL.set(Calendar.MINUTE, 0);
mEventClickListener.onNonEventSingleTap(RETCAL);
}
}
return super.onSingleTapConfirmed(e);
}
EventClickListener interface will looks like below:
public interface EventClickListener {
public void onEventClick(WeekViewEvent event, RectF eventRect);
public void onNonEventSingleTap(Calendar cal);
}
Now you will get Calendar object in your Activity or Fragment class:
#Override
public void onNonEventSingleTap(Calendar cal) {
// User cal object as Calendar
}
Hope this will help you.
hi mate y have this code and it works for me.
there you got two ways to add events.
the thing is that when you add the month variable it needs to be (month-1)
like if you want to add an event on july you must insert 7-1=6;
public List<WeekViewEvent> onMonthChange(int newYear, int newMonth) {
// Populate the week view with some events.
List<WeekViewEvent> events = new ArrayList<WeekViewEvent>();
Calendar startTime = Calendar.getInstance();
startTime.set(Calendar.DAY_OF_MONTH, 19);
startTime.set(Calendar.HOUR_OF_DAY, 1);
startTime.set(Calendar.MINUTE, 0);
startTime.set(Calendar.MONTH, 10);
startTime.set(Calendar.YEAR, 2015);
Calendar endTime = (Calendar) startTime.clone();
endTime.set(Calendar.DAY_OF_MONTH, 19);
endTime.set(Calendar.HOUR_OF_DAY, 5);
endTime.set(Calendar.MINUTE, 0);
endTime.set(Calendar.MONTH, 10);
endTime.set(Calendar.YEAR, 2015);
WeekViewEvent event = new WeekViewEvent(0, "Epoca", startTime, endTime);
event.setColor(getResources().getColor(R.color.orange));
events.add(event);
startTime = Calendar.getInstance();
startTime.set(2015, 10, 19, 6, 00);
endTime = Calendar.getInstance();
endTime.set(2015, 10, 19, 9, 00);
WeekViewEvent event2 = new WeekViewEvent(0,"00kjbhjbhjbjbhj",startTime, endTime);
event2.setColor(getResources().getColor(R.color.orange));
events.add(event2);
return events;
}
hope it helps.
may be the issue is your events are added but u have set the event month as startTime.set(Calendar.MONTH, date_month); it is not the previous month. so your events are added on the same date of previous month. check that.. if thats the case then just replace that line with
startTime.set(Calendar.MONTH, date_month+1);
Related
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;
}
} );
}
I want to create spinner which has
8:00-8:30 AM 8:30-9:00 AM 9:00-9:30 AM
time slot I done with the ArrayList like
8:00 AM 9:00 AM 10:00 AM
and so on.
I got the arraylist like
ArrayList[08:00:AM, 09:00:AM, 10:00:AM, 11:00:AM, 12:00:PM, 13:00:PM, 14:00:PM, 15:00:PM, 16:00:PM, 17:00:PM, 18:00:PM, 19:00:PM, 20:00:PM, 21:00:PM]
This is my code:
public class MainActivity extends AppCompatActivity {
ArrayList<String> hours = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initCustomTimeSpinner();
}
private void initCustomTimeSpinner() {
Spinner spinnerCustom = (Spinner) findViewById(R.id.spinner2);
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:a");
SimpleDateFormat startHourFormat = new SimpleDateFormat("HH");
cal.set(Calendar.HOUR_OF_DAY, 8);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
int startHour = Integer.parseInt(startHourFormat.format(cal.getTime()));
Log.e("startHour", Integer.toString(startHour));
Log.e("withot format Starttime", cal.getTime().toString());
SimpleDateFormat endHourFormat = new SimpleDateFormat("HH");
cal.set(Calendar.HOUR_OF_DAY, 21);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
int endHour = Integer.parseInt(endHourFormat.format(cal.getTime()));
Log.e("endHour", Integer.toString(endHour));
Log.e("withot format End time", cal.getTime().toString());
String test = sdf.format(cal.getTime());
Log.e("TEST", test);
for (int i = startHour; i <= endHour; i++) {
cal.set(Calendar.HOUR_OF_DAY, i);
hours.add(sdf.format(cal.getTime()));
System.out.println("ArrayList" + hours);
}
}
}
Here is simple example of building time-slots using Java 8 Time API:
public static void printTimeSlots(LocalTime startTime, LocalTime endTime, int slotSizeInMinutes) {
for (LocalTime time = startTime, nextTime; time.isBefore(endTime); time = nextTime) {
nextTime = time.plusMinutes(slotSizeInMinutes);
if (nextTime.isAfter(endTime))
break; // time slot crosses end time
System.out.println(time + "-" + nextTime);
}
}
Test
printTimeSlots(LocalTime.parse("08:00"), LocalTime.parse("17:00"), 30);
Output
08:00-08:30
08:30-09:00
09:00-09:30
09:30-10:00
10:00-10:30
10:30-11:00
11:00-11:30
11:30-12:00
12:00-12:30
12:30-13:00
13:00-13:30
13:30-14:00
14:00-14:30
14:30-15:00
15:00-15:30
15:30-16:00
16:00-16:30
16:30-17:00
Test #2, demonstrating misaligned end time
printTimeSlots(LocalTime.parse("10:05"), LocalTime.parse("11:55"), 15);
10:05-10:20
10:20-10:35
10:35-10:50
10:50-11:05
11:05-11:20
11:20-11:35
11:35-11:50
Or course, if you don't want to be limited to slot size in minutes, you can using TemporalAmount instead of number of minutes:
public static void printTimeSlots(LocalTime startTime, LocalTime endTime, TemporalAmount amountToAdd) {
for (LocalTime time = startTime, nextTime; time.isBefore(endTime); time = nextTime) {
nextTime = time.plus(amountToAdd);
if (nextTime.isAfter(endTime))
break; // time slot crosses end time
System.out.println(time + "-" + nextTime);
}
}
Test
printTimeSlots(LocalTime.parse("10:05:15"),
LocalTime.parse("11:55:00"),
Duration.ofMinutes(15).plusSeconds(25));
10:05:15-10:20:40
10:20:40-10:36:05
10:36:05-10:51:30
10:51:30-11:06:55
11:06:55-11:22:20
11:22:20-11:37:45
11:37:45-11:53:10
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?
I am using alam kanak week view in my app. I want show title in calender. Please help!
// my code
public List<WeekViewEvent> onMonthChange(int newYear, int newMonth) {
// Populate the week view with some events.
List<WeekViewEvent> events = new ArrayList<WeekViewEvent>();
Calendar startTime = Calendar.getInstance();
Calendar endTime = (Calendar) startTime.clone();
WeekViewEvent event;
List<ScheduleModel> contacts = db.getAllSchedule();
for (int i = 1; i <= 4; i++) {
for (ScheduleModel cn : contacts) {
startTime = Calendar.getInstance();
startTime.set(Calendar.HOUR_OF_DAY, cn.getStart_hour());
startTime.set(Calendar.MINUTE, cn.getStart_minute());
startTime.set(Calendar.DAY_OF_WEEK, cn.getDay() + 1);
startTime.set(Calendar.MONTH, newMonth - 1);
startTime.set(Calendar.YEAR, newYear);
endTime = (Calendar) startTime.clone();
endTime.set(Calendar.HOUR_OF_DAY, cn.getEnd_hour());
endTime.set(Calendar.MINUTE, cn.getEnd_minute());
event = new WeekViewEvent(5, getEventTitle(startTime, cn.getSubject()), startTime, endTime);
event.setColor(Color.parseColor(cn.getBg_color()));
events.add(event);
}
}
return events;
}
private String getEventTitle(Calendar time, String subject) {
return String.format("Event %s of %02d:%02d %s/%d", subject, time.get(Calendar.HOUR_OF_DAY), time.get(Calendar.MINUTE), time.get(Calendar.MONTH) + 1, time.get(Calendar.DAY_OF_MONTH));
}
Picture:
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;
}
}