The following two tabs change content below.
Hi, I have written and developed this site to share my experience and ideas with other colleagues. I also started to prepare interview questions and answers for job seekers. I hope it will help you a lot.

How to integrate google calendar api in android application? Describing the all required steps one by one.

  1. Create and simple android project using Android Studio. Like below I shared the screenshot of the newly created project.fresh_project
  2. Get a SHA1 fingerprint.In a command prompt, run the following command to get the SHA1 fingerprint you will use to enable the API
  3. For Window:
    keytool -exportcert -alias androiddebugkey -keystore C:\Users\Khushvinders\.android\debug.keystore -list –v
    For Linux:
    keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -list -v
  4. When asked for a keystore password, enter “android”       Screenshot of SHA1sh1
  5. Now before to start any development we have turn on the Google Calendar API using below steps:
    1. Use this wizard to create or select a project in the Google Developers Console and automatically turn on the API. Click Continue, and then Go to credentials.
    2. On the Add credentials to your project page, click the Cancel button.
    3. At the top of the page, select the OAuth consent screen tab. Select an Email address, enter a Product name if not already set, and click the Save button.
    4. Select the Credentials tab, click the Create credentials button and select OAuth client ID.
    5. Select the application type Android.
    6. Copy the SHA1 fingerprint from Step 2 into the Signing-certificate fingerprint field.
    7. In the Package name field, enter com.kpblog.googlecalendar
    8. Click the Create button.
  6. So now you are ready to start development. And add the following dependency into your build.gradle file compile ‘com.google.android.gms:play-services-auth:9.0.2’
    compile ‘pub.devrel:easypermissions:0.1.5’
    compile(‘com.google.api-client:google-api-client-android:1.22.0’) {

        exclude group: ‘org.apache.httpcomponents’
    }

    compile(‘com.google.apis:google-api-services-calendar:v3-rev218-1.22.0’) {
        exclude group: ‘org.apache.httpcomponents’
    }
  7. In the AndroidManifest.xml add the following permissions and Meta-Data
    Permission:

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />

    In the <application> tag add

    <meta-data
    android:name=”com.google.android.gms.version”
    android:value=”@integer/google_play_services_version” />

  8. Now all configuration are done you need to integrate API into Activity
  9. To get the list of already created event list                                                                                                    private com.google.api.services.calendar.Calendar mService = null;
    private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {     private Exception mLastError = null;
        private boolean FLAG = false;     public MakeRequestTask(GoogleAccountCredential credential) {
            HttpTransport transport = AndroidHttp.newCompatibleTransport();
            JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
            mService = new com.google.api.services.calendar.Calendar.Builder(
                    transport, jsonFactory, credential)
                    .setApplicationName(“Google Calendar API Android Quickstart”)
                    .build();
        }     /**
    * Background task to call Google Calendar API.
    * @param params no parameters needed for this task.
    */
    @Override

        protected List<String> doInBackground(Void… params) {
            try {
                getDataFromApi();
            } catch (Exception e) {
                e.printStackTrace();
                mLastError = e;
                cancel(true);
                return null;
            }
            return null;
        }     /**
    * Fetch a list of the next 10 events from the primary calendar.
    * @return List of Strings describing returned events.
    * @throws IOException
    */
    private void getDataFromApi() throws IOException {

            // List the next 10 events from the primary calendar.
    DateTime now = new DateTime(System.currentTimeMillis());

            List<String> eventStrings = new ArrayList<String>();
            Events events = mService.events().list(“primary”)
                    .setMaxResults(10)
                    .setTimeMin(now)
                    .setOrderBy(“startTime”)
                    .setSingleEvents(true)
                    .execute();
            List<Event> items = events.getItems();
            ScheduledEvents scheduledEvents;
            scheduledEventsList.clear();
            for (Event event : items) {
                DateTime start = event.getStart().getDateTime();
                if (start == null) {
                    start = event.getStart().getDate();
                }
                scheduledEvents = new ScheduledEvents();
                scheduledEvents.setEventId(event.getId());
                scheduledEvents.setDescription(event.getDescription());
                scheduledEvents.setEventSummery(event.getSummary());
                scheduledEvents.setLocation(event.getLocation());
                scheduledEvents.setStartDate(start.toString());
                scheduledEvents.setEndDate(“”);
                StringBuffer stringBuffer = new StringBuffer();
                if(event.getAttendees()!=null) {
                    for (EventAttendee eventAttendee : event.getAttendees()) {
                        if(eventAttendee.getEmail()!=null)
                          stringBuffer.append(eventAttendee.getEmail() + ”       “);
                    }
                    scheduledEvents.setAttendees(stringBuffer.toString());
                }
                else{
                    scheduledEvents.setAttendees(“”);
                }
                scheduledEventsList.add(scheduledEvents);
                   System.out.println(“—–“+event.getDescription()+”, “+event.getId()+”, “+event.getLocation());
                  System.out.println(event.getAttendees());
                 eventStrings.add(
                       String.format(“%s (%s)”, event.getSummary(), start));
            }
        }     @Override
        protected void onPreExecute() {
            mOutputText.setText(“”);
            mProgress.show();
        }     @Override
        protected void onPostExecute(List<String> output) {
            mProgress.hide();
            System.out.println(“——————–“+scheduledEventsList.size());
            if (scheduledEventsList.size()<=0) {
                mOutputText.setText(“No results returned.”);
            } else {
                eventListAdapter = new EventListAdapter(CalendarActivity.this, scheduledEventsList);
                eventListView.setAdapter(eventListAdapter);
            }
        }     @Override
        protected void onCancelled() {
            mProgress.hide();
            if (mLastError != null) {
                if (mLastError instanceof GooglePlayServicesAvailabilityIOException) {
                    showGooglePlayServicesAvailabilityErrorDialog(
                            ((GooglePlayServicesAvailabilityIOException) mLastError)
                                    .getConnectionStatusCode());
                } else if (mLastError instanceof UserRecoverableAuthIOException) {
                    startActivityForResult(
                            ((UserRecoverableAuthIOException) mLastError).getIntent(),
                            CalendarActivity.REQUEST_AUTHORIZATION);
                } else {
                    mOutputText.setText(“The following error occurred:\n”
                            + mLastError.getMessage());
                }
            } else {
                mOutputText.setText(“Request cancelled.”);
            }
        }
    }
  10. To add the new Event :                                                                                                                                      void insertEvent(String summary, String location, String des, DateTime startDate, DateTime endDate, EventAttendee[] eventAttendees) throws IOException {
        Event event = new Event()
                .setSummary(summary)
                .setLocation(location)
                .setDescription(des);     EventDateTime start = new EventDateTime()
                .setDateTime(startDate)
                .setTimeZone(“America/Los_Angeles”);
        event.setStart(start);     EventDateTime end = new EventDateTime()
                .setDateTime(endDate)
                .setTimeZone(“America/Los_Angeles”);
        event.setEnd(end);     String[] recurrence = new String[] {“RRULE:FREQ=DAILY;COUNT=1”};
        event.setRecurrence(Arrays.asList(recurrence));     event.setAttendees(Arrays.asList(eventAttendees));     EventReminder[] reminderOverrides = new EventReminder[] {
                new EventReminder().setMethod(“email”).setMinutes(24 * 60),
                new EventReminder().setMethod(“popup”).setMinutes(10),
        };
        Event.Reminders reminders = new Event.Reminders()
                .setUseDefault(false)
                .setOverrides(Arrays.asList(reminderOverrides));
        event.setReminders(reminders);     String calendarId = “primary”;
        //event.send
    if(mService!=null)

          mService.events().insert(calendarId, event).setSendNotifications(true).execute();
    }

Application screenshots are here :

createevent             createevent

Full code you can download from here : GoogleCalendar

11,026 total views, 29 views today

20 thoughts on “How to integrate google calendar api in android application”

    1. Have you completed 5th point as i mention on this post? like to add project on google console and other OAuth process. because as per your error it seems there is some wrong-configuration happen. Please re-check and let me know if still you are facing same issue.

  1. Sir, I have imported your code just to check how it works, but after creating an event it doesn’t show any event in google calendar.Can you please let me know the actual reason?

    1. Hi Pushpendra,

      Before to add any event you able to login with gmail account? and make sure you are using coming dates (not past dates) because in this app its only showing coming dates events. or you can also check your register event on web google calendar ..

  2. Hi sir,

    I imported your code and run but i got an error like com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
    com.kpblog.googlecalendar W/System.err: {
    com.kpblog.googlecalendar W/System.err: “code” : 400,
    com.kpblog.googlecalendar W/System.err: “errors” : [ {
    com.kpblog.googlecalendar W/System.err: “domain” : “global”,
    com.kpblog.googlecalendar W/System.err: “message” : “Invalid attendee email.”,
    com.kpblog.googlecalendar W/System.err: “reason” : “invalid”
    com.kpblog.googlecalendar W/System.err: } ],
    com.kpblog.googlecalendar W/System.err: “message” : “Invalid attendee email.”
    com.kpblog.googlecalendar W/System.err: }

    but i registered my app in to google developer console , please give me the solution

  3. Hello Sir,
    I solved that problem by refreshing Google Calendar.But sir faced a new one If I select the date 8 march but when I see in google calendar then the event is seen to be added to either 9 or 10 march I mean one or two dates ahead.Is this the problem of Standard Time or anything else.

  4. Hi, thanks for the post. It works well on my app.

    However, I want to integrate it in my own app that I am making. But each time I am calling createEventAsync method at the end it is giving me mService = null so it does not insert the event. Any suggestions?

    Also is it possible to make the CalendarActivity in a fragment class and use it? Please provide some insights. I am trying to make my app insert events like how you do but, I want to call the method from another activity.

    Thanks in advance

  5. hi, ur blog is very helpful. I really like it. Can i also know how to update the events added on google calendar??

  6. Hi, i have very simple requirement to add event using Async Task , Do i need to simply call your point 10 in Async Background task or i need to add
    private com.google.api.services.calendar.Calendar mService = null;
    private class MakeRequestTask extends AsyncTask<Void, Void, List> { private Exception mLastError = null;
    private boolean FLAG = false; public MakeRequestTask(GoogleAccountCredential credential) {
    HttpTransport transport = AndroidHttp.newCompatibleTransport();
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    mService = new com.google.api.services.calendar.Calendar.Builder(
    transport, jsonFactory, credential)
    .setApplicationName(“Google Calendar API Android Quickstart”)
    .build();
    also in addition to other settings. Presently my app is workng fine using Acivity to insert event.

  7. hi code works fine when normally tested but when we uploaded apk to googleplaystore and fetch the events at the time i got error like ” following error occured null” i.e it goes to onCancelled() method and the errror will rise, so please solve the error . thank you.

    1. Please follow the 5th point to enable API and then simply use gradle dependency for further intigration. If you have any other error please share the full exception stack trace.

  8. Program type already present: android.support.v4.app.BackStackRecord$Op
    Message{kind=ERROR, text=Program type already present: android.support.v4.app.BackStackRecord$Op, sources=[Unknown source file], tool name=Optional.of(D8)}

Leave a Reply

Your email address will not be published. Required fields are marked *