Adding Calendar Events – Phonegap Android plugin

Alright, I worked on this sometime back and I will share this with you. I was looking to programmatically  add events to the native Android calendar from a Phonegap android app. There is not an official plugin that is available as of now. So I wrote a custom workaround for this. Again, I am not a Java developer and there might be better ways of writing the plugin code. But just wanted to share the code, and any feedback would just be appreciated.

Alright, let’s get started. So, there are two files that I developed. One is the CalendarEventPlugin.java file which has the plugin’s JAVA code. The other one is the CalendarEventPlugin.js file which is the javascript interface of the plugin. At this point, if you are not sure of what goes into writing a custom Phonegap plugin for Android, then you might want to have a look at this. I am using Phonegap 2.2.0 for my purpose. There has been newer version of Phoengap that is available now, 2.4.0 being the latest at the time of writing. So you can use the latest version as well, but do check the documentation once, there might be some changes.

Check the two files out. I have inline comments that will help you to understand. Rest, is very simple to grasp. Now let’s check how to use and implement this plugin into your Phonegap Android project.

1) Firstly you have to add these two files to your Phonegap Android project. Add the CalendarEventPlugin.js file inside assets/www/ folder and provide a reference to it in your index.html file, like this

<script type="text/javascript" charset="utf-8" src="CalendarEventPlugin.js"></script>

2) Then create a directory inside your project’s src folder that matches the package name of CalendarEventPlugin.java class. For our case make a directory – /org/apache/cordova/plugin inside src and then paste CalendarEventPlugin.java file inside it. If you change the package name, make sure to change the directory structure as well. The package name can be found at the top of CalendarEventPlugin.java file.

3) Next thing to do is to register the plugin in the config file – open res/xml/config.xml and then add the plugin details given below to the <plugins></plugins> section of the XML file. The name attribute is the Java class name and the value is the path of the class. This should match the package name.

<plugin name="CalendarEventPlugin" value="org.apache.cordova.plugin.CalendarEventPlugin"/>

4) And then call the plugin inside your javascript (your script.js file or so) code like this. (You can call this inside a button click handler or so),
   window.addcalendareventplugin(function(val){
        alert(val);   //once success message come and you have tested it, you can remove this alert.
    });

Once everything runs fine, you will see that when you click a button or so in your demo app and it calls the callback function in step 4, the native Calendar Add event is popped up with values already set in it (which you can change in the java file of the plugin). From there on its just the normal way of adding events to Calendar.
Hope this helps!!

Note

  • I have tried this on an Android 4.0 device (Galaxy S3) and it works. I have not really tried this on lower Android versions.

31 thoughts on “Adding Calendar Events – Phonegap Android plugin

  1. Hi joseph,
    Very well explained thank you. Unfortunately I could not get it to work – i got the following error:
    ReferenceError: Can’t find variable: cordova at file:///android_asset/www/js/CalendarEventPlugin.js:3
    I am using cordova 2.3. Do you have any idea why that would be? If i get it to work i will test it on iphone and let you know if it works. FYI i have been trying to get this “add calendar event” feature to work for almost a month now and still no luck – am about to go mad!

      • Right now this has been set in the Java class. Yes you can set them from js and pass it to java in the cordova.exec() method call’s argument array.

      • Which version of Android are you using it for? If you are checking this in a Android 2.2 or 2.3 simulator you will get an Error alert. As I said in my blog post, I have tested this only in an Android 4.0 device and it works.

  2. Thanks for your quick response. Yes i assumed it was because i am using Android 2.2 simulator. Will try on device tomorrow.

    So could i do the following?
    window.addcalendareventplugin = function(callback){
    var startDate = new Date();
    var endDate = new Date();
    endDate.setDay(endDate.getDay() + 1);
    cordova.exec(callback,function(err){
    callback(‘Error: ‘ + err);

    },”CalendarEventPlugin”,”addCalendarEvent”,[startDate, endDate , “A new event”, ]);

    window.addcalendareventplugin(function(val){ });
    }

    If not sorry for wasting your time and could you give me a correct example please.

    Thanks again joseph

    • Thomas,

      Yes test it on a device. But it should work from Android 4. Lower versions I am not too sure.
      For the date changes that you are doing, it looks good to me. Yes you can pass the values in an array to the Java class. Make sure to read them in the Java class.
      And no you are not wasting my time. I appreciate your comments and the fact that you liked my post.
      Thanks and good luck.

  3. A nice piece of code, however, it is really not needed. Fortunately for Android (on most devices 2.2 or later), you can use an undocumented Intent to bring up a new calendar entry. Use the PhoneGap plugin WebIntent, and the address “vnd.android.cursor.item/event”, and pass in whatever fields you want to pre-populate, and a dialog will be shown to the user to save the appointment. Here is the js function I use in my apps:

    Sharing.AddEvent = function (callback_success, callback_fail, subj, loc, desc, strt, end, cal_id) {
    console.log(‘Sharing:AddEvent(Android)’);
    var extras = {};
    extras[“title”] = subj;
    extras[“location”] = loc;
    extras[“description”] = desc;
    extras[“beginTime”] = strt;
    extras[“endTime”] = end;
    window.plugins.WebIntent.startActivity({
    action: WebIntent.ACTION_EDIT,
    type: “vnd.android.cursor.item/event”,
    extras: extras
    },
    function() {callback_success },
    function(e) {
    callback_fail(e);
    }
    );
    Again, the WebIntent is from the plugin. You can use this for getting calendar entries, updating, sending sms or email, just with different “type” addresses.

  4. Joseph, thanks for you time into this.
    I’m trying to integrate your sollution, but I’m having some problems.
    I’m unsing an HTC device with android 4.0.3, cordova 2.5.0
    I use your java and js files. I added to my index the js and plugin to config.xml
    My html code look’s like this:
    function addEventCalendar() {
    window.addcalendareventplugin(function(val){
    alert(val); //once success message come and you have tested it, you can remove this alert.
    });
    }
    I use this code on a button.
    And I’m stuck with Error: Error on the device.

    Can you give me a hint?

    Thanks

  5. Thanks Mark for you input.
    I tried the solution proposed by you and I can’t figure it out.
    I got the plugin from this repository
    https://github.com/phonegap/phonegap-plugins/tree/master/Android/WebIntent/
    I added webintent.js to my www folder and into index.html
    Also the plug in into config.xml
    I created a function, simplify a little you code just for test.

    function addWebEventCalendar() {
    var extras = [];
    extras[“title”] = ‘Subject Of Calendar’;
    extras[“location”] = ‘Test Location’;
    extras[“description”] = ‘Test Description’;

    var startDate = new Date();
    var endDate = new Date();

    endDate.setDate(6);

    extras[“beginTime”] = startDate;
    extras[“endTime”] = endDate;

    window.plugins.WebIntent.startActivity({
    action: WebIntent.ACTION_EDIT,
    type: “vnd.android.cursor.item/event”,
    extras: extras
    },
    function() {alert(‘Add Success!’); },
    function(e) {alert(‘Add Fail: ‘+e); }
    );
    }

    I use this function on a button.
    I get the error “WebIntent is not defined” on this line: action: WebIntent.ACTION_EDIT
    I’m shure I’m missing something.

    Can you give us a little hint / help?

    Thanks for all your trouble.

  6. I have a statement before adding the function like this
    document.addEventListener(“deviceready”, onDeviceReady, false);
    Suppose to wait for device to get ready. (I not shure) I’m new to cordova/android apps
    And also I’m doing the actual call after a long time from starting the device.

    I found this http://stackoverflow.com/questions/15146858/webintent-error-using-phonegap-2-4-reference-error-webintent-is-not-defined
    related on the same error I get.

    There it suggest to change the line action: WebIntent.ACTION_EDIT with: action: window.plugins.webintent..ACTION_EDIT
    But that does not work also. I get an other error: my whole addWebEventCalendar is undefined.

    Joseph: The function with the plug in is also packed in the zip I send it to you last night. Maybe we can figure it out and post an working example some where because is really helpful and I could not find on the web an example of webIntent working with calendar.

  7. hello,
    thank you for your post. It very helpful for me. I am able to store events into native calendar but have one problem. every time I got the screen for done button press while saving data in native calendar…. Please help how I save events into calendar without user notification.

    • The done button notification comes from the javascript part of the plugin. There is an alert(); statement. You need to comment that out in this block,

      window.addcalendareventplugin(function(val){
      alert(val); //once success message come and you have tested it, you can remove this alert.
      });

      Thanks

  8. while running application it shows an error unfortunately calendar was stopped…..
    How can i over come that error…..

  9. Hi All, I want to save html in Android Phone’s calendar that is coming from REST WCF. HTML has Calendar events like below:
    BEGIN:VCALENDAR
    PRODID:-//RyanFarley.com//iCalendar Sample MIMEDIR//EN
    VERSION:2.0
    METHOD:PUBLISH
    BEGIN:VEVENT

    DTSTART:20131202T000000Z
    DTEND:20131202T120000Z
    LOCATION:TestLocation
    CATEGORIES:
    TRANSP:OPAQUE
    SEQUENCE:0
    UID:RFCALITEM635218305696290701
    DTSTAMP:20131202T000000Z
    DESCRIPTION:TestDesc
    SUMMARY:TestSummary

    PRIORITY:5
    CLASS:PUBLIC
    BEGIN:VALARM
    TRIGGER:PT15M
    ACTION:DISPLAY
    DESCRIPTION:Reminder
    PRIORITY:5
    END:VALARM
    END:VEVENT
    END:VCALENDAR

    I want to save this in my Android calendar. Thanks

  10. I am developing hybrid (html5 – phone gap – eclipse IDE) android application. I will try to insert an event in default android calendar, while as I follow the above mentioned steps, I need the clarification on step 2 (which place to put the “CalendarEventPlugin.java”). Share me any sample program that will help for me. I am new to this concept.

    • Put it in the src folder along with other Android Activity classes. The steps are pretty detailed in fact. Try it out and let me know if you have difficulties.

      • hi joseph,
        once I have included (CalendarEventPlugin.java) that above mentioned path this but still iam not able to add the event on calendar. I have following error logged such as

        Error Log:
        09-19 11:53:47.472: E/Posix(5475): [CDS]Libcore_io_Posix-throwErrnoException, functionName: remove; errno: No such file or directory
        09-19 11:53:47.474: E/Posix(5475): [CDS]Libcore_io_Posix-throwErrnoException, functionName: remove; errno: No such file or directory
        09-19 11:53:47.474: E/Posix(5475): [CDS]Libcore_io_Posix-throwErrnoException, functionName: remove; errno: No such file or directory
        09-19 11:53:47.477: E/Posix(5475): [CDS]Libcore_io_Posix-throwErrnoException, functionName: remove; errno: No such file or directory
        09-19 11:53:47.561: E/Posix(5475): [CDS]Libcore_io_Posix-throwErrnoException, functionName: access; errno: No such file or directory
        09-19 11:53:47.561: E/Posix(5475): [CDS]Libcore_io_Posix-throwErrnoException, functionName: access; errno: No such file or directory
        09-19 11:53:48.439: E/Web Console(5475): Uncaught TypeError: Object # has no method ‘exec’ at file:///android_asset/www/CalendarEventPlugin.js:5
        09-19 11:53:48.511: E/Web Console(5475): Uncaught Error: Module nl.x-services.plugins.calendar.Calendar does not exist. at file:///android_asset/www/cordova.js:1375

        Html code:

        Hello World

        $(document).ready(function () {
        window.addcalendareventplugin(function(val){
        alert(val); //once success message come and you have tested it, you can remove this alert.
        });
        });

        Welcome

        Best,
        Raviraj

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s