Show me the code! – By Davanum Srinivas

December 5, 2007

Android – Use ATOM/GData API to access the Google Calendar

Filed under: Uncategorized — Davanum Srinivas @ 11:15 pm

Here’s a sample on how to use access Google Calendar from Android


1

Just enter your userid (with @gmail.com), password, select any date and press lookup button.

Here’s the meat of the application:

import com.google.android.gdata.client.AndroidXmlParserFactory;
import com.google.android.gdata.client.JakartaGDataClient;
import com.google.wireless.gdata.calendar.client.CalendarClient;
import com.google.wireless.gdata.calendar.data.EventEntry;
import com.google.wireless.gdata.calendar.data.When;
import com.google.wireless.gdata.calendar.parser.xml.XmlCalendarGDataParserFactory;
import com.google.wireless.gdata.client.QueryParams;
import com.google.wireless.gdata.data.Feed;
import com.google.wireless.gdata.parser.GDataParser;
    /**
     * When the user clicks on the lookup button we use the ATOM/GData API to fetch the
     * details of events for a specific date
     * @param view
     */
    public void onClick(View view) {
        XmlCalendarGDataParserFactory factory = new XmlCalendarGDataParserFactory(new AndroidXmlParserFactory());
        JakartaGDataClient dataClient = new JakartaGDataClient();

        // Generate the URL for a private ATOM feed in google calendar 
        String url = "http://www.google.com/calendar/feeds/" +
                dataClient.encodeUri(mUserId.getText().toString()) + "/private/full";
        QueryParams params = dataClient.createQueryParams();
        String pad1 = (mMonth + 1) < 10 ? "0" : "";
        String pad2 = mDay < 10 ? "0" : "";
        params.setParamValue("start-min", mYear + "-" + pad1 + (mMonth + 1) + "-" + pad2 + mDay + "T00:00:00");
        params.setParamValue("start-max", mYear + "-" + pad1 + (mMonth + 1) + "-" + pad2 + mDay + "T23:59:59");
        url = params.generateQueryUrl(url);
        Log.i("GoogleContacts", "URL :" + url);

        CalendarClient client = new CalendarClient(dataClient, factory, url);
        try {
            Log.i("GoogleContacts", "BaseFeedUrl:" + client.getBaseFeedUrl());

            String user = mUserId.getText().toString();
            String password = mPassword.getText().toString();
            Log.i("GoogleContacts", "userid:" + user);
            Log.i("GoogleContacts", "password:" + password);

            // Get the google token
            String authToken = client.getAuthToken(user, password);
            Log.i("GoogleContacts", "Token:" + authToken);

            // Use the token and access the actual feed.
            java.io.InputStream is = dataClient.getFeedAsStream(url, authToken);
            GDataParser parser = factory.createParser(is);
            Feed feed = parser.init();

            int totalResults = feed.getTotalResults();
            Log.i("GoogleContacts", "Results:" + totalResults);

            // wade thru the entries and pick interesting information
            EventEntry entry = null;
            String[] items = new String[totalResults];
            for (int i = 0; i < totalResults; i++) {
                entry = (EventEntry) parser.readNextEntry(entry);
                Log.i("GoogleContacts", "Entry ID:" + entry.getId());
                Log.i("GoogleContacts", "Entry Title:" + entry.getTitle());
                Log.i("GoogleContacts", "Update Date:" + entry.getUpdateDate());
                When when = entry.getFirstWhen();
                Date time1 = zulu.parse(when.getStartTime());
                Date time2 = zulu.parse(when.getEndTime());
                Log.i("GoogleContacts", "Date/Time: FROM " + zulu2.format(time1) + " TO " + zulu2.format(time2));
                items[i] = zulu2.format(time1) + " - " + zulu2.format(time2) + " : " + entry.getTitle();
            }

            // Display the information in the list view
            ListView listView = (ListView) findViewById(R.id.data);
            listView.setAdapter(new ArrayAdapter(this,
                    android.R.layout.simple_list_item_1,
                    items));
        } catch (Exception e) {
            Log.e("GoogleContacts", e.toString(), e);
        }
    }

Download the sources and Application – GoogleCalendar.zip

34 Comments »

  1. You are really incredible! Bravo!!! Where do you find gdata api descriptions, I can’t find any inside android?

    Comment by milan — December 6, 2007 @ 12:13 pm

  2. I’ve found it on the web, thanks (http://code.google.com/apis/gdata/javadoc/)… BR, Milan

    Comment by milan — December 6, 2007 @ 12:22 pm

  3. Great work. I was going to investigate on that still unveiled API. Didn’t really know how to authenticate: you showed us the way. You save much of our time. Many thanks. Edouard

    Comment by Edouard Mercier — December 6, 2007 @ 2:28 pm

  4. Sorry to ask, I must be stupid. Cannot find the way to use the rest of the Google API, in order, for instance to get the list of all calendars for an account. I am using the “http://www.google.com/calendar/feeds/default/allcalendars/full” URL with the “CalendarClient”, but every time my “CalendarEntry” list is empty.

    Any hint, please? Thank you for your time.
    Your Android blog rocks!
    Edouard

    Comment by Edouard Mercier — December 12, 2007 @ 5:05 pm

  5. Hi

    thanks a lot for your application, it’s very useful. But, I received one error when try to execute your application.

    com.google.wireless.gdata.client.AuthenticationException: Unable to login. java.io.IOException: Read error (return code 0; error code 5; errno 0)

    E/OpenSSLSocketImpl(548): Read error (return code 0; error code 5; errno 0)
    W/GDataClient(548): Exception from POST (authUri: /accounts/ClientLogin): java.io.IOException: Read error (return code 0; error code 5; errno 0)

    Cpuld you help me please!!!

    Comment by rut — February 6, 2008 @ 6:51 am

  6. In the m5 SDK the getAuthToken() has been removed from the CalendarClient class. Does anybody know where to receive the AuthTokens now?

    Comment by Markus — February 14, 2008 @ 2:42 pm

  7. Hi, i have the same problem, I need getAuthToken method and with this new SDK i cannot use it.

    Comment by Alex — February 15, 2008 @ 3:57 am

  8. Hi,
    I have the same problem with getAuthToken,
    There is some solution?

    Thank you,

    Comment by MariaJose — February 22, 2008 @ 5:48 am

  9. Hi, I implement this class to can retrieve the AuthToken :

    import java.io.IOException;

    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpException;
    import org.apache.commons.httpclient.methods.PostMethod;

    import com.google.android.gdata.client.JakartaGDataClient;
    import com.google.wireless.gdata.client.QueryParams;

    public class GoogleAccountConnector {
    static final String googleAccountUrl = “https://www.google.com/accounts/ClientLogin”;

    public static String getAuthToken(String user, String password) {
    HttpClient httpclient = new HttpClient();
    JakartaGDataClient dataClient = new JakartaGDataClient();
    QueryParams params = dataClient.createQueryParams();
    params.setParamValue(“accountType”, “GOOGLE”);
    params.setParamValue(“Email”, user);
    params.setParamValue(“Passwd”, password);
    params.setParamValue(“service”, “cl”);
    params.setParamValue(“source”, “sebi-fullcontact-1.0”);
    PostMethod post = new PostMethod(params
    .generateQueryUrl(googleAccountUrl));
    post.addRequestHeader(“Content-Type”,
    “application/x-www-form-urlencoded”);
    try {
    int status = httpclient.executeMethod(post);
    } catch (HttpException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    } catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    }
    try {
    return extractTokenFromResponse(“Auth”, post
    .getResponseBodyAsString());
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    return null;

    }

    private static String extractTokenFromResponse(String token, String response) {
    String result = null;
    String tokenPrefix = (new StringBuilder()).append(token).append(“=”)
    .toString();
    int startIdx = response.indexOf(tokenPrefix);
    if (startIdx >= 0) {
    int endIdx = response.indexOf(‘\n’, startIdx);
    if (endIdx > 0) {
    result = response.substring(startIdx + tokenPrefix.length(),
    endIdx);
    } else {
    result = response.substring(startIdx + tokenPrefix.length());
    }
    }
    return result;
    }
    }

    Comment by Sebi — March 24, 2008 @ 9:24 am

  10. Sebi,

    I tried your code. but error popup for the line:

    int status = httpclient.executeMethod(post);

    error msg:

    Exception processing async thread queue
    Exception processing async thread queue
    Timeout occurred while waiting for packet 1857.

    Any hint?

    Comment by Yadong — March 27, 2008 @ 2:14 am

  11. Did anybody get this to work on m5-15

    Comment by asd — April 8, 2008 @ 4:16 pm

  12. Does anyone have an example for creating a new entry

    Comment by Jan — April 29, 2008 @ 5:53 am

  13. what is that pic means?
    😉

    Comment by hao — May 28, 2008 @ 5:47 am

  14. Awesome, awesome, awesome, thank you so much for posting this

    Comment by Blank Calendar — September 14, 2008 @ 8:04 pm

  15. I have a working example for logging in. Hope it helps!

    private boolean clickSign() {
    String username = txtUsername.getText().toString();
    String password = txtPassword.getText().toString();

    XmlCalendarGDataParserFactory factory = new XmlCalendarGDataParserFactory(new AndroidXmlParserFactory());
    AndroidGDataClient dataClient = new AndroidGDataClient(this.getContentResolver());

    try {
    String googleAccountUrl = “https://www.google.com/accounts/ClientLogin”;

    HttpClient httpclient = new DefaultHttpClient();
    QueryParams params = dataClient.createQueryParams();
    params.setParamValue(“accountType”, “GOOGLE”);
    params.setParamValue(“Email”, username);
    params.setParamValue(“Passwd”, password);
    params.setParamValue(“service”, “cl”);
    params.setParamValue(“source”, “sebi-fullcontact-1.0”);
    HttpPost post = new HttpPost(params.generateQueryUrl(googleAccountUrl));
    post.setHeader(“Content-Type”, “application/x-www-form-urlencoded”);

    HttpResponse res = httpclient.execute(post);
    StatusLine status = res.getStatusLine();

    sundroid.data.setString(“GoogleResponse”, “” + status.getStatusCode() + ” ” + status.getReasonPhrase());

    return (status.getStatusCode() == HttpStatus.SC_OK);
    } catch (Exception e1) {
    Log.e(TAG, e1.toString(), e1);
    sundroid.data.setString(“GoogleResponse”, “Exception – ” + e1.toString());
    } finally {
    dataClient.close();
    }
    return false;
    }

    Comment by Paul Bourdeaux — October 2, 2008 @ 10:10 am

  16. EDIT: You can ignore the sundroid.data.setString line. That is internal code that is not relevant to the rest.

    Comment by Paul Bourdeaux — October 2, 2008 @ 10:12 am

  17. I can’t download your source and applications. Plz check link.

    Comment by [Sniper]zangchung — June 1, 2009 @ 2:13 am

  18. The zip file gives a 404 error 😦

    Can someone share the zip file? You can send it to me at nehagp2007 at gmail dot com

    Comment by Natasha — June 27, 2009 @ 10:53 am

  19. downloading is showing an error saying currently this is not found on the server.
    Will you check it once and can suggest any other location?
    Thanks && Rgds,
    Sunny.

    Comment by sunny — November 19, 2009 @ 12:22 am

  20. Can someone share me the zip file to demo.gcal@gmail.com

    Comment by sunny — November 19, 2009 @ 12:23 am

  21. I got some problems on using calendar API, does anyone send GoogleCalendar.zip above to me, thanks

    Error: getauthToken() can not get authToken

    chris.yh.gardner@gmail.com

    Comment by chris — December 23, 2009 @ 3:58 am

  22. Hi all ,

    i am new to android,
    i want to develope calendar application in android.
    The application should show day view,month view and week view.
    i dont know how to start,can some one example with an calendar application.

    thanks and regards
    john

    Comment by Sasil — April 2, 2010 @ 4:33 am

  23. Can someone share me the zip file to yousonytone@gmail.com

    Comment by shrenik — April 25, 2010 @ 12:26 pm

  24. Can someone share me the zip file to novatnt@gmail.com

    Comment by Hi~~! — June 21, 2010 @ 8:59 pm

  25. awesome work . but Can someone share me the zip file to biplob.sust@gmail.com . i am eagerly waiting for this .please help me

    Comment by biplob — July 2, 2010 @ 7:19 pm

  26. Can someone share me the zip file to evehour@gmail.com

    Comment by LeeDH — November 29, 2010 @ 7:06 pm

  27. Where is the download zip file?
    So many users are saying the code is down.
    Why don’t you bother to put a working link for it or remove it.

    Comment by John — May 2, 2011 @ 4:40 am

  28. Can some one send me the source code zip file to mail id seshu45@gmail.com. Your help can be appreciated more. Have a Nice day to all.

    Comment by seshadri — June 1, 2011 @ 1:49 am

  29. can someone re-upload the zip file and post a link here., many thanks

    Comment by ds pctt — July 7, 2011 @ 5:44 am

  30. Can someone share this zip file. sawanmodi1@gmail.com

    Comment by sawan — August 9, 2011 @ 3:45 am

  31. Hello,

    I am trying to download this google calander example.Can someone send me this zip file to skumar.m226@gmail.com.

    thnks

    Comment by kumar — January 11, 2012 @ 10:31 am

  32. Can someone send the zip file to mail id vngenesis@gmail.com. Its really really urgent.
    Please help. Thanks

    Comment by Jennifer — January 25, 2012 @ 5:25 am

  33. Can someone send the zip file to mail id rubydul.ahsan@shurjomukhi.com.bd

    Comment by Rubyd — June 18, 2012 @ 11:31 pm

  34. Can someone share this zip file. sweetsunny818@gmail.com

    Comment by sunny — January 25, 2014 @ 4:23 am


RSS feed for comments on this post. TrackBack URI

Leave a comment

Create a free website or blog at WordPress.com.