Which is the right way to introduce data in Android's calendar? - android

I'm trying to make a calendar but I'm having some problems with it. I have all the information I need such as the day, the month, the hour, etc, but when I try to create the calendar it says that the application suddenly stopped. When I debug and look the LogCat, the error returned is: "Failed to find provider info for calendar" and it appears between the Checkpoint2 and the Checkpoint3.
The code to create the event when I have all the information is the next one:
private void crear()
{
Log.d("Crear Evento","Checkpoint 1");
this.alarm = 1; //ALARMA!!!!
Calendar cal = new GregorianCalendar(this.anyo,this.mes,this.dia,this.hora,this.minutos,0);
long startTime = cal.getTimeInMillis();
long endTime = startTime+3600000;
ContentResolver contentResolver = this.getContentResolver();
ContentValues event = new ContentValues();
Log.d("Crear Evento","Checkpoint 2");
Uri eventsUri = Uri.parse(getCalendarUriBase(this)+"events");
Cursor cursor = contentResolver.query(Uri.parse(getCalendarUriBase(this) ),new String[] { "calendar_id", "displayname" }, null,null, null);
Log.d("Crear Evento","Checkpoint 3");
cursor.moveToFirst();
// fetching calendars name
String CNames[] = new String[cursor.getCount()];
// fetching calendars id
int[] CalIds = new int[cursor.getCount()];
Log.d("Crear Evento","Checkpoint 4");
for (int i = 0; i < CNames.length; i++) {
CalIds[i] = cursor.getInt(0);
CNames[i] = cursor.getString(1);
cursor.moveToNext();
}
Log.d("Crear Evento","Cálculos previos sin problemas");
event.put("calendar_id", String.valueOf(CalIds[0]));
event.put("title", this.titulo);
event.put("description", this.descripcion);
event.put("eventLocation", this.lugar);
event.put("allDay", 0);
event.put("eventStatus", 1);
event.put("transparency", 0);
event.put("dtstart", startTime);
event.put("dtend", endTime);
event.put("hasAlarm", this.alarm);
try{
contentResolver.insert(eventsUri, event);
}catch(Exception e){
e.printStackTrace();
}
Log.d("Crear Evento", "¡Guardado sin problemas!");
}

Related

Reading all the events happened during 3 days from the calendar into my android app

I'm trying to log all the events which are happening for 3 days from today in my activity. I'm getting the following errors. Please help.
My Code :
public static long getStartOfDayInMillis() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis();
}
public static ArrayList<String> readCalendarEvent(Context context) {
Uri.Builder eventsUriBuilder;
eventsUriBuilder = Uri.parse("content://com.android.calendar/events").buildUpon();
ContentUris.appendId(eventsUriBuilder,getStartOfDayInMillis());
ContentUris.appendId(eventsUriBuilder, getStartOfDayInMillis() + 3*(24 * 60 * 60 * 1000));
Uri eventsUri = eventsUriBuilder.build();
Cursor cursor = context.getContentResolver()
.query(
eventsUri,
new String[] { "calendar_id", "title", "description",
"dtstart", "dtend", "eventLocation" }, null,
null, CalendarContract.Instances.DTSTART + " ASC");
// fetching calendars name
String CNames[] = new String[cursor.getCount()];
// fetching calendars id
nameOfEvent.clear();
startDates.clear();
endDates.clear();
descriptions.clear();
for (int i = 0; i < CNames.length; i++) {
nameOfEvent.add(cursor.getString(1));
startDates.add(getDate(Long.parseLong(cursor.getString(3))));
// endDates.add(getDate(Long.parseLong(cursor.getString(4))));
descriptions.add(cursor.getString(2));
CNames[i] = cursor.getString(1);
cursor.moveToNext();
}
return nameOfEvent;
}
I'm calling it to give logs of all the names of the events in the same Java class as..
results= readCalendarEvent(MyCalendarActivity.this);
for(int i=0;i< results.size();i++ )
Log.d("results",results.get(i));
I'm getting the following errors :
Caused by: java.lang.IllegalArgumentException: Unknown URL content://com.android.calendar/events/1448821800000/1448908200000
This is because you are using wrong URL. Replace with this:
eventsUriBuilder = Uri.parse("content://com.android.calendar/instances/when").buildUpon();
Or:
eventsUriBuilder = CalendarContract.Instances.CONTENT_URI.buildUpon()

Add an event to calendar

I'm using the following code (from developer site) for inserting an event in device calendar-
long calID = 1;
long startMillis = 0;
long endMillis = 0;
Calendar beginTime = Calendar.getInstance();
beginTime.set(2015, 9, 6, 7, 00);
startMillis = beginTime.getTimeInMillis();
Calendar endTime = Calendar.getInstance();
endTime.set(2015, 9, 6, 8, 45);
endMillis = endTime.getTimeInMillis();
ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues();
values.put(Events.DTSTART, startMillis);
values.put(Events.DTEND, endMillis);
values.put(Events.TITLE, "Test Title");
values.put(Events.DESCRIPTION, "Group workout");
values.put(Events.CALENDAR_ID, calID);
TimeZone tz = TimeZone.getDefault();
values.put(Events.EVENT_TIMEZONE, tz.getID());
Uri uri = cr.insert(Events.CONTENT_URI, values);
long eventID = Long.parseLong(uri.getLastPathSegment());
The code seems to work because I'm getting eventID of the inserted event.
After executing this, I'm not able to see the event in the calendar app. I tried with syncing the calendar from settings>accounts>google>calendar.
Is there something wrong in the code or any additional code that I've to add to see the events in the calendar?
Thanks to #Nobu Games, I solved the issue. The problem was calendarId = 1 was not associated with any of the calendar. I created a method to find out available calendarIds in the device using following code-
public MyCalendar [] getCalendar(Context c) {
String projection[] = {"_id", "calendar_displayName"};
Uri calendars;
calendars = Uri.parse("content://com.android.calendar/calendars");
ContentResolver contentResolver = c.getContentResolver();
Cursor managedCursor = contentResolver.query(calendars, projection, null, null, null);
if (managedCursor.moveToFirst()){
m_calendars = new MyCalendar[managedCursor.getCount()];
String calName;
String calID;
int cont= 0;
int nameCol = managedCursor.getColumnIndex(projection[1]);
int idCol = managedCursor.getColumnIndex(projection[0]);
do {
calName = managedCursor.getString(nameCol);
calID = managedCursor.getString(idCol);
m_calendars[cont] = new MyCalendar(calName, calID);
cont++;
} while(managedCursor.moveToNext());
managedCursor.close();
}
return m_calendars;
}
And then I'm able to see the events in the calendar.

How can I add events to Android default calendar on button click?

protected void addToCalendar()
{
final ContentResolver cr = this.getContentResolver();
Cursor cursor = cr.query(Uri.parse("content://com.android.calendar/calendars"), new String[]{ "_id", "displayName" }, null, null, null);
cursor.moveToFirst();
String[] calNames = new String[cursor.getCount()];
final int[] calIds = new int[cursor.getCount()];
Log.i("Cal Names Length", "Length of Cals:"+calNames.length);
Log.i("Names of calendar:", "Cal names:"+calNames.toString());
for (int i=0; i<calNames.length; i++)
{
calIds [i] = cursor.getInt(0);
calNames[i] = cursor.getString(1);
cursor.moveToNext();
Log.i("Calendar", "Cal_id:"+calIds[0]);
Log.i("Calendar", "Cal_Name:"+calNames[0]);
}
cursor.close();
ContentResolver cr = getContentResolver();
if(calIds.length > 0)
{
Log.i("in if condition", "Of calIds.length");
Calendar cal = Calendar.getInstance();
Date birth_date = null;
for (int i = 0; i < final_list.size(); i++)
{
obj = final_list.get(i);
String dateFromDB = obj.getmBirthday();
SimpleDateFormat parser = new SimpleDateFormat("MM/dd/yyyy");
try
{
birth_date = parser.parse(dateFromDB);
}
catch (java.text.ParseException e)
{
e.printStackTrace();
}
// event insert
int cal_id = calIds[0];
ContentValues values = new ContentValues();
values.put("calendar_id", cal_id);
Log.i("Calendar", "Cal_ID:"+cal_id);
values.put("title", obj.getmName());
Log.i("Title", "Title:"+obj.getmName());
values.put("dtstart", birth_date.getTime());
values.put("dtend", birth_date.getTime() + 1800*1000);
values.put("duration", 1800*1000 );
values.put("description", "Birthday Reminder");
values.put("allDay", 1);
values.put("rrule", "FREQ=YEARLY");
values.put("visibility", 0);
values.put("hasAlarm", 1);
cr.insert(Uri.parse("content://com.android.calendar/events"), values);
}
}
}
I have used this method on button click. When I click on the button ArrayList of Events should be added to Default calendar of Android Device. But here in this code, I am unable to see the event that is added to Calendar. And I even think that entry is not being added to calendar.
Thank you.
This is what I use, and it works in my code
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", startDate.getTimeInMillis());
intent.putExtra("endTime", endDate.getTimeInMillis());
intent.putExtra("title", title);
activty.startActivity(intent);
The event is added to android calendar, but it's not checked to see if the same event is already there (possible duplicate of the event)

How to add reminder in calendar

Hi i am implementing birthday reminder app on android. please tell me what is the procedure to set reminder on calendar. I have obtained the calendar in android .
You can use this for adding events in the Android Calendar.
GregorianCalendar startDate = new GregorianCalendar(Locale.ENGLISH);
startDate = CustomDateFormatter.formatScheduleDate(schedule.getScheduleStartDate());
GregorianCalendar endDate = new GregorianCalendar(Locale.ENGLISH);
endDate = CustomDateFormatter.formatScheduleDate(schedule.getScheduleEndDate());
try{
String[] projection = new String[] { "_id", "name" };
Uri calendars = Uri.parse("content://com.android.calendar/calendars");
Cursor managedCursor = mContext.getContentResolver().query(calendars, projection, "selected=1", null, null);
ContentValues event = new ContentValues();
long StartTime = startDate.getTimeInMillis();
long EndTime = endDate.getTimeInMillis();
// int nameColumn = managedCursor.getColumnIndex("name");
int idColumn = managedCursor.getColumnIndex("_id");
if(managedCursor.moveToFirst()){
// String calName = managedCursor.getString(nameColumn);
String calId = managedCursor.getString(idColumn);
// Log.e("Cal name", calName);
event.put("calendar_id", calId);
event.put("title", schedule.getScheduleType());
event.put("description", schedule.getScheduleTextContent());
event.put("dtstart", StartTime );
event.put("dtend", EndTime);
event.put("hasAlarm", 1);
Uri eventsUri = Uri.parse("content://com.android.calendar/events");
Uri calUri = mContext.getContentResolver().insert(eventsUri, event);
Uri remindersUri = Uri.parse("content://com.android.calendar/reminders");
event = new ContentValues();
event.put("event_id", Long.parseLong(calUri.getLastPathSegment()));
// Log.d("Event ID: ", calUri.getLastPathSegment());
event.put("method",1);
event.put("minutes",0);
mContext.getContentResolver().insert(remindersUri, event);
}
managedCursor.close();
}catch(Exception ex){
ex.printStackTrace();
}

sync event added programmatically with google calendar in android

I am trying to add an event to the android calendar, and I specify that the event will be added to the gmail calendar in order to sync with the Google calendar automatically.
The problem is events added programmatically don't sync with Google calendar, but if I add it manual on the phone it does sync with Google calendar. I don't know why.
This is the code that I use to add the event:
ArrayList<MyCalendar> calendars = new ArrayList<MyCalendar>();
String[] projection = new String[] { "_id", "name" };
Uri calUri = getCalendarURI(false);
Cursor managedCursor = managedQuery(calUri, projection, "selected=1",
null, null);
String calName = null;
String calId = null;
if (managedCursor.moveToFirst()) {
int nameColumn = managedCursor.getColumnIndex("name");
int idColumn = managedCursor.getColumnIndex("_id");
do {
calName = managedCursor.getString(nameColumn);
calId = managedCursor.getString(idColumn);
calendars.add(new MyCalendar(Integer.parseInt(calId), calName));
} while (managedCursor.moveToNext());
}
Toast.makeText(getBaseContext(), calName + " " + calId,
Toast.LENGTH_LONG).show();
Calendar cal = Calendar.getInstance();
ContentValues event = new ContentValues();
event.put("calendar_id", 2);
event.put("title", "Test Event2");
event.put("description", "Hiii Buddy");
long startTime = cal.getTimeInMillis();
long endTime = cal.getTimeInMillis() + 60 * 60 * 1000;
event.put("dtstart", startTime);
event.put("dtend", endTime);
event.put("allDay", 0);
event.put("eventStatus", 1);// tentative 0, confirmed 1 canceled 2
event.put("visibility", 3);// default 0 confidential 1 private 2
// public 3
event.put("transparency", 0);// opaque 0 transparent 1
event.put("hasAlarm", 1); // 0 false, 1 true
Uri eventsUri = getCalendarURI(true);
Uri url = getContentResolver().insert(eventsUri, event);
So the event successfully added to calendar but it doesn't show up in the Google calendar at the web (don't sync) but if I add the event manually it does sync !!!
You can sync your event after adding it by this function,It's worked for me(in API 8 and later):
public static void syncCalendar(Context context, String calendarId) {
ContentResolver cr = context.getContentResolver();
ContentValues values = new ContentValues();
values.put(CalendarContract.Calendars.SYNC_EVENTS, 1);
values.put(CalendarContract.Calendars.VISIBLE, 1);
cr.update(
ContentUris.withAppendedId(getCalendarUri(),
Long.parseLong(calendarId)), values, null, null);
}
Try this code to insert an event into the android calendar as well as google calendar:
ContentValues values = new ContentValues();
cal_id = String.valueOf(p1);
values.put("calendar_id", p1);
values.put("title", title1);
values.put("allDay", 0);
values.put("dtstart", settime);
values.put("dtend", cal.getTimeInMillis()+60*60*1000);
values.put("description", desc1);
values.put("visibility", 0);
values.put("transparency", 0);
values.put("hasAttendeeData", 1);
values.put("hasAlarm", 0);
event = cr.insert(EVENTS_URI, values);
event1=event;
dat1 = event.toString();
long id=-1;
if (event != null)
{
id = Long.parseLong(event.getLastPathSegment());
ContentValues values1 = new ContentValues();
values1.put("event_id", id);
values1.put("method", 1); //METHOD_ALERT
Uri reminder = Uri.parse(getCalendarUriBase(this) + "reminders");
this.getContentResolver().insert(reminder, values1);
if(s.length() > 0 || partmail.length() > 0)
{
//REQUIRES FOLLOWING CODE
This code is used to add the event sync'ed to the google calendar
ContentValues attendees = new ContentValues();
attendees.put("event_id", id);
attendees.put("attendeeEmail", partmail1);
attendees.put("attendeeRelationship", 2);//RELATIONSHIP_ATTENDEE
attendees.put("attendeeStatus", 3); //ATTENDEE_STATUS_INVITED
attendees.put("attendeeType", 1); //TYPE_REQUIRED
id1=(int)id;
alarmid = (int) id;
Uri attendeesUri = null;
if (Integer.parseInt(Build.VERSION.SDK) >= 8 )
{
attendeesUri = Uri.parse("content://com.android.calendar/attendees");
}
else if(Integer.parseInt(Build.VERSION.SDK) < 8)
{
attendeesUri = Uri.parse("content://calendar/attendees");
}
this.getContentResolver().insert(attendeesUri, attendees);
Toast.makeText(this, "Task Scheduled Successfully", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this, "Could not create Task!", Toast.LENGTH_SHORT);
}
// reminder insert
Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(this) + "reminders");
values = new ContentValues();
values.put( "event_id", id);
values.put( "method", 1 );
values.put( "minutes", 0 );
cr.insert( REMINDERS_URI, values );
Get Calendar's Uri since it differs for API levels such as till 8, greater than 8 and greater than 11.
private String getCalendarUriBase(Context con) {
String calendarUriBase = null;
Uri calendars = Uri.parse("content://calendar/calendars");
Cursor managedCursor = null;
try {
managedCursor = managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
// eat
}
if (managedCursor != null) {
calendarUriBase = "content://calendar/";
} else {
calendars = Uri.parse("content://com.android.calendar/calendars");
try {
managedCursor = managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
// statement to print the stacktrace
}
if (managedCursor != null) {
calendarUriBase = "content://com.android.calendar/";
}
}
return calendarUriBase;
}
Use the google calender api provided here
The above reference is somewhat general as Android doesn’t provide an official API. So, another solution more android specific is An Android Tutorial–Programming with Calendar
which contains a working example too. Also, be careful at Permission Declaration like READ_CALENDAR , WRITE_CALENDAR

Categories

Resources