Monday, October 7, 2013

Creating a calendar in Xamarin Monodroid

I had to create a calendar in Android using Xamarin and found it really tough initially. So I thought of writing this so that it becomes easy for others to just follow.

Do it before you forget
It is important to add permissions so to make sure that the code works well on the device.
<uses-permission android:name="android.permission.READ_CALENDAR" />
 <uses-permission android:name="android.permission.WRITE_CALENDAR" />

we will be using the CalendarContract so make sure that the minimum SDK level is set to 14

How to create Calendar
First you have to query the columns and create the properties that the calendar will have.

var uri = CalendarContract.Calendars.ContentUri;
            ContentValues val = new ContentValues();
            val.Put(CalendarContract.Calendars.InterfaceConsts.AccountName, AccountName);
            val.Put(CalendarContract.Calendars.InterfaceConsts.AccountType, CalendarContract.AccountTypeLocal);
            val.Put(CalendarContract.Calendars.Name, "My Calendar");
            val.Put(CalendarContract.Calendars.InterfaceConsts.CalendarDisplayName, "Silverspot");
            val.Put(CalendarContract.Calendars.InterfaceConsts.CalendarColor, Android.Graphics.Color.Red);       
            val.Put(CalendarContract.Calendars.InterfaceConsts.OwnerAccount, AccountName);
            val.Put(CalendarContract.Calendars.InterfaceConsts.Visible, true);
            val.Put(CalendarContract.Calendars.InterfaceConsts.SyncEvents, true);
            uri = uri.BuildUpon()
                .AppendQueryParameter(CalendarContract.CallerIsSyncadapter, "true")
                .AppendQueryParameter(CalendarContract.Calendars.InterfaceConsts.AccountName, AccountName)
                .AppendQueryParameter(CalendarContract.Calendars.InterfaceConsts.AccountType, CalendarContract.AccountTypeLocal)
            var calresult = ContentResolver.Insert(uri, val);

CallerIsSyncadapter will give you more powers to customize the calendar and create you own calendar instead of adding events in the already existing default calendar. If you dont want it you may set it to false. ContentResolver.Insert will create a new calendar in the native calendar app. This will return a url that will have the calendar ID that will be used in creating events against the calendar that you just created. In my next post ill explain how to create event in the calendar that you just created.