How to show title in alamkanak week view - java

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:

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;
}
} );
}

How to show the next day's date from the selected date in the datepicker dialog in Android?

I am currently showing the today's date and day & as well as tomorrow's date and day in individual layouts while at the page load. But my requirement is that
1) Whatever the date I'm choosing from the Datepicker, it should display on the 1st layout
2) The next day's date should display on the second layout.
My 1st requirement is working fine without any problem.,(i.e), Whatever the day I'm choosing, it's displaying on the 1st layout. No issue, but I'm having problem with my 2nd requirement.
Consider if I choose 25-May-2018 on the DatePicker, it's displaying on the 1st layout as expected, but instead of displaying next day's date as 26-May-2018, it's displaying as 26-Jun-2018. But I need it to work in such a way that if I choose 25-May-2018 in Datepicker, the selected date should get displayed on 1st layout & the immediate next day's date (26-May-2018) should displayed on next layout. This should be applicable to whatever the date I'm choosing in the Datepicker.
Where have I gone wrong ?
Here's my Activity.Java:
public class PrivacyPolicyActivity extends AppCompatActivity {
LinearLayout layout1, layout2, layout3, todayLayout, tomorrowLayout;
ImageView calendarImgView;
TextView todayDate;
TextView todayDay;
TextView tommmorrowDate;
TextView tommorrowDay;
TextView todayLabel;
TextView tommorrowlabel;
DatePickerDialog datePickerDialog;
Calendar calendar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_privacy_policy);
calendar = Calendar.getInstance();
Date today = calendar.getTime();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
final DateFormat dateFormat = new SimpleDateFormat("dd-MMM");
DateFormat day = new SimpleDateFormat("EEEE");
layout1 = (LinearLayout) findViewById(R.id.layout1);
layout2 = (LinearLayout) findViewById(R.id.layout2);
layout3 = (LinearLayout) findViewById(R.id.layout3);
todayDate = (TextView) findViewById(R.id.todayDate);
todayDate.setText(dateFormat.format(today));
todayDay = (TextView) findViewById(R.id.todayDay);
todayDay.setText(day.format(today));
tommmorrowDate = (TextView) findViewById(R.id.tommmorrowDate);
tommmorrowDate.setText(dateFormat.format(tomorrow));
tommorrowDay = (TextView) findViewById(R.id.tommorrowDay);
tommorrowDay.setText(day.format(tomorrow));
todayLayout = (LinearLayout) findViewById(R.id.todayLayout);
tomorrowLayout = (LinearLayout) findViewById(R.id.tomorrowLayout);
todayLabel = (TextView) findViewById(R.id.todayLabel);
tommorrowlabel = (TextView) findViewById(R.id.tommorrowlabel);
calendarImgView = (ImageView) findViewById(R.id.calendarImgView);
calendarImgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
datePickerDialog = new DatePickerDialog(PrivacyPolicyActivity.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
// SimpleDateFormat dateandmonth = new SimpleDateFormat("dd-MMM");
// Date date = new Date();
// String reqddate = dateandmonth.format(date);
//todayDate.setText(day + "/" + (month + 1) + "/" + year);
int cyear = datePicker.getYear();
int cmonth = datePicker.getMonth();
int cday = datePicker.getDayOfMonth();
Calendar cld = Calendar.getInstance();
cld.set(cyear, cmonth, cday);
SimpleDateFormat format = new SimpleDateFormat("dd-MMM");
String strDate = format.format(cld.getTime());
todayDate.setText(strDate);
SimpleDateFormat dayfmt = new SimpleDateFormat("EEEE");
String dayselected = dayfmt.format(cld.getTime());
todayDay.setText(dayselected);
int nextYear = datePicker.getYear() + 1;
int nextMonth = datePicker.getMonth() + 1;
int nextDay = datePicker.getDayOfMonth() + 1;
Calendar nextcld = Calendar.getInstance();
nextcld.set(nextYear, nextMonth, nextDay);
SimpleDateFormat tom_format = new SimpleDateFormat("dd-MMM");
String tom_date = tom_format.format(nextcld.getTime());
tommmorrowDate.setText(tom_date);
SimpleDateFormat day_fmt = new SimpleDateFormat("EEEE");
String tom_day = day_fmt.format(cld.getTime());
tommorrowDay.setText(tom_day);
}
}, year, month, dayOfMonth);
datePickerDialog.show();
}
});
}
}
Why you increasing Month and year also with 1 ?
int nextYear = datePicker.getYear() + 1;
int nextMonth = datePicker.getMonth() + 1;
int nextDay = datePicker.getDayOfMonth() + 1;
just increase nextDay.
cld.add(Calendar.DATE, 1);
Solution
calendarImgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
datePickerDialog = new DatePickerDialog(PrivacyPolicyActivity.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
// SimpleDateFormat dateandmonth = new SimpleDateFormat("dd-MMM");
int cyear = datePicker.getYear();
int cmonth =datePicker .getMonth();
int cday = datePicker.getDayOfMonth();
Calendar cld = Calendar.getInstance();
cld.set(cyear, cmonth, cday);
SimpleDateFormat format = new SimpleDateFormat("dd-MMM");
String strDate = format.format(cld.getTime());
todayDate.setText(strDate);
SimpleDateFormat dayfmt = new SimpleDateFormat("EEEE");
String dayselected = dayfmt.format(cld.getTime());
todayDay.setText(dayselected);
cld.add(Calendar.DATE, 1);
SimpleDateFormat day_fmt = new SimpleDateFormat("EEEE");
String tom_day = day_fmt.format(cld.getTime());
tommorrowDay.setText(tom_day);
}
},year,month,dayOfMonth);
datePickerDialog.show();
}
});
In you Datepicker callback place the following code to show the next day.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DATE, datePicker.getDayOfMonth());
calendar.set(Calendar.MONTH, datePicker.getMonth());
calendar.set(Calendar.YEAR, datePicker.getYear());
calendar.add(Calendar.DATE, 1);
SimpleDateFormat tom_format = new SimpleDateFormat("dd-MMM");
String tom_date = tom_format.format(calendar);
tommmorrowDate.setText(tom_date);

Cannot automatically add event to Google Calendar

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;
}

How to add event in alamkanak week view

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);

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