推荐安卓开发神器(里面有各种UI特效和android代码库实例)
参考地址: http://jimblackler.net/blog/?p=151&cpage=1#comments
The Android phone operating system provides close integration with three excellent services from Google; email, address book and calendar. In addition it has a thriving third party app scene with a great variety of free and commercial applications on the Market. In theory this should mean that apps can provide new services to the user based on the Google service data they have already synced on the phone.
However in the case of calendar data this has proven a bit tricky. Google provide an API to access calendar data via the internet, and this can be used directly from Android apps. Unfortunately this also requires a working data connection, time and battery life to get at the data. In addition it will need the app to prompt for the user's credentials (user name and password).
All this seems unnecessary when the data you want is right there on the phone already. Since there is an API that any application can use to access the user's contact (address book) data directly on the phone without going to the internet. It's called android.provider.Contacts and is documented here. So why doesn't android.provider.Calender exist?
The answer
The answer is that is does exist – although it is not documented, and it is not included with the standard Google Android SDK. It is a little-known fact that it is possible to download the Android source, force the provider classes to be included by removing the @hide annotation that protects it, and make your own version of the SDK. This can be compiled against apps from which calendar queries can then be made.
This is how I originally built my app Quick Calendar – a 'lite' read only version alternative to the built-in calendar application released early 2009. This uses the same data used by the built-in calendar application, already synced onto users' Android phones. Judging by my inbox it's been the most popular hobby application I've ever put out. I've since had a number of inquires from other developers as to how I managed get at the internal calendar data on Android.
Firstly I would say that getting at the data by a custom-build SDK is possible but awkward. For one thing it is a pain keeping up to date with the latest changes and staying in sync with the Android Eclipse plug in.
The good news is you don't actually need to use the calendar provider SDK classes to get at the data. Android exposes data across applications by using a feed system similar to web-based feeds, and query syntax similar to SQL. As a result, provided your app has the correct user permission (android.permission.READ_CALENDAR) you can query the database from the names, and continue to use standard SDKs such as 1.5 or 1.6. In the absence of specific SDK support for calendars, it's only slightly less convenient to directly use the provider's internal URIs (e.g. "content://calendar/calendars") directly.
Warning
At this point I should point out that there's a reason why Google haven't officially exposed the internal calendar APIs. This is probably because they anticipate future changes to the calendar format. Once they've published an SDK the formats are to some extent set in stone and they'd like to avoid that. In my experience the formats have been stable since I first discovered the feed. However, don't be surprised if future firmware changes break any apps that use the feed. In this event you'll have to update your app and re-upload it to the Market. It's not that big a worry, certainly not enough to avoid using this great feature - the ability to present users' calendar data in new ways to them.
Example
I've uploaded an example project to http://svn.jimblackler.net/jimblackler/trunk/workspace/AndroidReadCalendarExample. All the calendar reading code is in http://svn.jimblackler.net/jimblackler/trunk/workspace/AndroidReadCalendarExample/src/net/jimblackler/readcalendar/Example.java.
To read the calendar data in your own app firstly add android.permission.READ_CALENDAR under <manifest> in your application's AndroidManifest.xml.
Please note that you will probably have to use a real phone to test your app in development, because the emulator included with the SDK does not include the Google services (there will simply be no calendar database present to query).
Then get an android.content.ContentResolver and make a query to content://calendar/calendars to enumerate all the available calendars
on the phone. The '_id' column will give you the calendar's ID (referenced in events). You can get rough documentation of all the columns supported by looking at core/java/android/provider/Calendar.java. (As mentioned previously, this file is part of the public open source Android project but is not part of the official Android SDK from Google)
PLAIN TEXTJAVA:
ContentResolver contentResolver = context.getContentResolver();
final Cursor cursor = contentResolver.query(Uri.parse("content://calendar/calendars"),
(new String[] { "_id", "displayName", "selected" }), null, null, null);
while (cursor.moveToNext()) {
final String _id = cursor.getString(0);
final String displayName = cursor.getString(1);
final Boolean selected = !cursor.getString(2).equals("0");
System.out.println("Id: " + _id + " Display Name: " + displayName + " Selected: " + selected);
}
Once you have a calendar ID you can use your ContentResolver object to obtain the events from that calendar. Note how a 'where' clause of 'Calendars._id=??' is employed to fetch only events of that particular calendar. This clause could query whichever columns your app required, using an SQL-like syntax. Note also how the Uri.Builder was used to build up a URL including date bounds for the query.
PLAIN TEXTJAVA:
Uri.Builder builder = Uri.parse("content://calendar/instances/when").buildUpon();
long now = new Date().getTime();
ContentUris.appendId(builder, now - DateUtils.WEEK_IN_MILLIS);
ContentUris.appendId(builder, now + DateUtils.WEEK_IN_MILLIS);
Cursor eventCursor = contentResolver.query(builder.build(),
new String[] { "title", "begin", "end", "allDay"}, "Calendars._id=" + id,
null, "startDay ASC, startMinute ASC");
while (eventCursor.moveToNext()) {
final String title = eventCursor.getString(0);
final Date begin = new Date(eventCursor.getLong(1));
final Date end = new Date(eventCursor.getLong(2));
final Boolean allDay = !eventCursor.getString(3).equals("0");
System.out.println("Title: " + title + " Begin: " + begin + " End: " + end +
" All Day: " + allDay);
}
Note that all dates in the calendar format are stored as UTC (the number of milliseconds that have elapsed between midnight 1st January 1970 and the event in Greenwich UK).
This is the basics of calendar access on Android. I haven't covered all the columns (these can be seen in the SDK source linked above) and I haven't covered modification. Notheless I hope this information allows other developers to build great calendar-aware apps for Android. Please do leave queries in the comments here, and if you use this information to make an app please do tell us about it in the comments here.
Update
To access the Corporate Calendar on Motorola devices, use "content://calendarEx" in place of "content://calendar".
Update 2
For Android devices using 2.2 (Froyo) or greater, where previously you had content://calendar you should write content://com.android.calendar
How timely! Just what I have been looking for. Thanks for taking the time to document
jimblackler on October 26, 2009 at 6:01 pm
I expect you can add/modify by the feed but I haven’t had to do this myself so not worked it out. I would look at what the documented providers do (e.g. the contacts provider) for reference.
Alternatively if it is a low volume of events it may be best to use activities to get the user to confirm the add/modify manually. I do this in my BBC Listings application.
Joe on October 30, 2009 at 5:32 pm
Excellent! Thanks for the rundown, you’ve saved me a lot of pain…
Matt on November 5, 2009 at 9:13 am
Is there a way to run this example in the SDK’s emulator? For me it fails here:
final Cursor cursor = contentResolver.query(Uri.parse(”content://calendar/calendars”), …);
returning “null” everytime.
jimblackler on November 5, 2009 at 9:25 am
Matt, I don’t know if there are any publicly available Android emulators that support Google Calendar. Without a calendar on the phone, there is no service to query.
Jason on November 13, 2009 at 10:43 pm
I know it’s asking a lot, but could you create a “quick add” event app.
I used a Palm Treo 650 before my Droid, and the day-view of the Palm’s calendar was used more than the phone portion.
I constantly check, add, reschedule events on the calendar. And it has notification events (with defaults for alert tone/vibrate and time before event)
jimblackler on November 14, 2009 at 1:01 am
Hi Jason, did you know if you long click on the day title in the event list in QC that it prompts you to add an event on that day?
Ram on November 20, 2009 at 3:46 pm
Hi Jim,
Thanks for the beautiful write-up and the code. I have a quick question. Is it possible to query the Calendar database with event’s creation time/date? If yes then could you please tell how.
Also, I am capturning the change notifications from calendar using the ContectObserver but my problem is how do I distinguish if it’s add event or delete event?
Thanks in advance for your help.
-Ram
jimblackler on November 20, 2009 at 4:02 pm
Re. your first question, I haven’t had to do that, but have you looked at the available columns in the source for the CalendarProvider, as linked in the article?
Re. the second question I haven’t used the class you mention so cannot advise there.
Ray on November 23, 2009 at 2:52 am
Hi Jim,
I want to write a calendar app which can read and write meetings.
Is there any possibility to get a calendar app like your ‘Quick Calendar’ run in the Android SDK to set some “example meetings”? When I install your app on my SDK i get every time the error: “The application Calendar Storage (process com.android.calendar) has stopped unexpectedly. Please try again.” Don’t know how to solve, so you’re my last chance! :-)
Thank you in advance for your help!
Ray
jimblackler on November 23, 2009 at 9:36 am
Hi Ray
Can you run the built-in Google Calendar application on the device? Usually called “Calendar” in the applications selector.
Also could you let me know which device you have?http://jimblackler.net/blog/wp-admin/edit-comments.php?p=151#comments-form
Jim
Ram on November 23, 2009 at 12:38 pm
thanks Jim.
Another question please. How to update or delete the calendar entries? Could you please mention how the query looks like?
Thanks,
-Ram
Ray on November 23, 2009 at 3:05 pm
Hi Jim,
I don’t have any Android device to test my programs. I can only test them with the Android emulator, but emulator has a calendar app installed. I tried to install the calendar with the Calendar.apk from http://code.google.com/p/android/issues/detail?id=1389 and the CalendarProvider.apk but when i click on the icon the same error comes.
Currently I’m using Android 2.0 emulator. I alredy tried it with 1.5 and 1.6, but everytime with the same error!
Greetings
Ray
tibo on November 25, 2009 at 8:33 pm
If you want to write events to a calendar you can follow this tutorial [->http://android.arnodenhond.com/tutorials/calendar]
Varun on December 1, 2009 at 5:22 am
Hi Jim,
I am new to android and I was trying to use Android’s Native Calendar.
Thanks for an excellent write-up.
I had couple of questions regarding the usage of the native calendar.
I am trying to build an application which can interact with the calendar to add/edit/delete events from the native calendar.
In your blog you are talking about reading the events from the calendar. Is it possible to perform the CRUD operations on the native calendar using ContentProviders alone ?
Thanks in advance,
Varun
jimblackler on December 1, 2009 at 7:35 am
> Is it possible to perform the CRUD operations on the native calendar using ContentProviders alone ?
I believe it is although I prefer to write events through Intents myself (this gives the user a chance to confirm the calendar event before adding).
Sean Neilan on December 16, 2009 at 10:11 pm
Dear Jim,
I am trying to get this to work with android sdk 2.0.1. I had put the Example class from your project into my standard android project & it didn’t work. I noticed that there wasn’t a Calendar class in the Android.jar file in eclipse.
Is it possible that I need to recompile the android 2.0.1 sdk and include the calendar class?
Should I be using a different android sdk?
Thank you for time,
Sean
jimblackler on December 16, 2009 at 10:20 pm
You shouldn’t have to rebuild the SDK no. The point of this technique is that it doesn’t actually require the Calendar classes.
Sean Neilan on December 17, 2009 at 6:28 pm
Is it possible that it doesn’t work with android sdk 2.0.1? Which android sdk did you use?
Sean Neilan on December 17, 2009 at 6:50 pm
Actually, I think I meant which version of the android OS you used because the phone I am running has android 2.0.1 on it. There’s no way to debug this inside of the emulator so I’ll have to reflash my phone if necessary.)
Is there a way to find the sqlite file itself perhaps?
Please excuse me for asking so many questions. I thank you very much for your time in this.
lauren on December 26, 2009 at 8:40 pm
thank you! this was very helpful.
Mo on January 7, 2010 at 11:21 pm
Hi Jim,
Fantastic blog. Can you give me an advice on what I need to extract events from calendar instead of the calendar as a whole. Am planning to build an application which pulls events from the phone calendar then send it as sms messages to contacts.
Many thnx
jimblackler on January 8, 2010 at 3:18 pm
Hi Mo
The demo shows querying of all events in a given time range.
You can add sqlite SELECT terms to the query to query on any columns you choose.
Jim
Matt on January 18, 2010 at 4:06 pm
I can’t get this working. I’ve downloaded the source code and compiled and run on my g1 to no avail. I’ve downloaded your quickcalendar app and that works fine… any ideas,
Matt on January 18, 2010 at 10:22 pm
Well it works but it just shows a blank screen with the app title. I have also set up multiple appointments for the week to test…
Any ideas, this would really help.
I have a G1 running stock android 1.6
thanks
jimblackler on January 18, 2010 at 10:24 pm
Matt, look at the console log output. It’s not a fully working application, it just shows how the calendar information can be read, which is written to the console rather than the phone screen.
Matt on January 19, 2010 at 9:00 am
Perfect, don’t believe i didn’t read the code properly. thanks. For some reason my console isn’t outputting anything so i sightly modified and used a textview to output. Now all i have to work out is why i can’t write to the calendar even though permissions are added (any ideas on that one will be much appreciated )
Thanks again
Alberto on January 22, 2010 at 5:11 am
Hi Jim, great blog post. I’d been looking for something like this for a while. Would you happen to know if it’s possible to do this with Gmail’s content provider as well to read e-mail? I made a first attempt but couldn’t get it to work but maybe you’ve had better luck?
jimblackler on January 22, 2010 at 11:41 am
I haven’t looked into it Alberto. It’s an interesting question. You can often get a clue about that kind of thing by running ‘adb logcat -d’ on a USB connected PC with SDK, using the app you are interested in and watching the log output. It may well give content provider URLs in the output.
Alberto on January 26, 2010 at 8:10 am
Thanks, I’ll give that a try. There’s a new app called Slide Screen that just came out that’s displaying both calendar info as well as Gmail so I imagine they must be using a similar method to what you described here. I’ll let you know if I’m able to make progress. If anyone’s got this working (Gmail) please let us know!
Laurent on January 27, 2010 at 10:17 pm
Thanks Jim
What about corporate calendar? is that just using a different Uri for the query?
I’d like to make a small app that registers my visits to customers…
I did that on windows mobile but I cannot find out how to do it on android
Richard Sewell on January 29, 2010 at 8:04 pm
Jim - can you share anything the Intents you use to add calendar events ? I couldn’t see those in your example.
I’ve tried adding events from code, following
http://android.arnodenhond.com/tutorials/calendar
and
http://www.developer.com/ws/article.php/3850276/Working-with-the-Android-Calendar.htm
While I did manage to add events, I also broke my Google Calendar in a way which means that it won’t sync to the cloud any more. Also, I can no longer edit my calendar via the Web interface. Apparently it is waiting for a human at Google to review it!
That made me a little nervous about adding events directly to the database, so I am hoping to find a safer way…
jimblackler on January 30, 2010 at 12:49 pm
Sure Richard… try this.
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", startTime);
intent.putExtra("endTime", startTime + duration);
intent.putExtra("title", title);
intent.putExtra("eventLocation", location);
intent.putExtra("description", description);
startActivity(intent);
Adding events by intent has limitations and advantages.
Limitations: Only one event at a time, requires user to approve each one.
Advantages: Doesn’t require a permission flag in the application, user has the chance to modify the event and select calendar the to use.
Richard Sewell on January 31, 2010 at 9:45 am
Jim - thanks - that’s perfect. And (I hope) it will be harder to break the calendar database with that approach.
Did you ever stray into creating repeating events, by the way ?
arnold on February 5, 2010 at 3:12 pm
Jim - thanks for the clear blog..
You say it’s possible to build a android.jar with the calendar.
This would be very helpfull for me to build a app.
But i keep solving errors when i remove the @hide in the calendarprovider.
And i can’t seem to find much on that item on the web.
Can you sent me in the good direction with this..or do you maybe have a android.jar with the calendar class?
Thanks.
John on February 21, 2010 at 1:14 am
Thanks for posting this, it really was helpful when I started integrating my project with the android calendar. I found a few other helpful sources as well, and have compiled a “wrapper” class to wrap the calendar in a more usable way.
/* * Copyright (C) 2010 John Malizia * * Licensed under the Apache License, Version 2.0 (the “License”); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an “AS IS” BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.homework.org; import java.util.ArrayList; import com.homework.org.HomeworkException.Exception_ID; import android.app.Activity; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; public class CalendarEvent{ public static long calendarID = -1; public static String calendarName = null; final static String STRING_CALENDAR_EVENTS_URI = “content://calendar/events”; final static String STRING_CALENDAR_URI = “content://calendar/calendars”; final static Uri eventsUri = Uri.parse(STRING_CALENDAR_EVENTS_URI); final static Uri calendars = Uri.parse(STRING_CALENDAR_URI); //Exceptions final String STRING_CALENDAR_NOT_SET = “Calendar not set”; final String STRING_ASSIGNMENT_NOT_FOUND = “Assignment not found”; //End Exceptions public Activity a = null; /** * @param a * Constructor */ public CalendarEvent(Activity a) { this.a = a; } /** * @param strTitle as the Title of the event * @param strDescription as the description of the event * @param startTime as the time in millis the event begins * Note: StartTime/EndTime are the same for this method because * We only want to show the assignment for the day it’s due. */ public void insertEvent(String strTitle, String strDescription,long startTime) throws HomeworkException { if (!(calendarID == -1)) { ContentValues event = new ContentValues(); event.put(”calendar_id”, calendarID);event.put(”title”, strTitle); event.put(”description”, strDescription); event.put(”dtstart”, startTime-homeworkproject.END_DATE_MODIFIER); event.put(”dtend”, startTime-homeworkproject.END_DATE_MODIFIER); event.put(”allDay”, 1); // 0 for false, 1 for true event.put(”eventStatus”, 1); event.put(”visibility”, 0); event.put(”transparency”, 0); event.put(”hasAlarm”, 1); // 0 for false, 1 for true a.getContentResolver().insert(eventsUri, event); } else throw new HomeworkException(STRING_CALENDAR_NOT_SET,Exception_ID.CALENDAR_NOT_SELECTED); } /** * Returns int with the number of rows deleted - Should never return > 1 * @param iAssignmentID as the eventID to remove */ public int removeEvent(long iAssignmentID) throws HomeworkException { if (!(calendarID == -1)) { Uri deleteEventUri = Uri.withAppendedPath(eventsUri, String.valueOf(iAssignmentID)); return a.getContentResolver().delete(deleteEventUri, null,null); } else { throw new HomeworkException(STRING_CALENDAR_NOT_SET,Exception_ID.CALENDAR_NOT_SELECTED); } } /** * Returns boolean specifying if the passed EventID is in the Calendar */ public boolean contains(long iAssignmentID) throws HomeworkException { if (!(calendarID == -1)) { String[] projection = new String[] { “title”,”_id” }; Cursor managedCursor = a.managedQuery(eventsUri, projection,”Events._id=”+iAssignmentID, null, null); while(managedCursor.moveToNext()) { return true; } } else throw new HomeworkException(STRING_CALENDAR_NOT_SET,Exception_ID.CALENDAR_NOT_SELECTED); return false; } /** * Returns int with the number of rows updated - Should never return > 1 * @param iAssignmentID as the eventID to update * @param whereArgs as the Set arguments see Where class */ public int updateEvent(long iAssignmentID,ArrayList whereArgs) throws HomeworkException { if (!(calendarID == -1)) { if(contains(iAssignmentID)) { Uri updateEventUri = Uri.withAppendedPath(eventsUri, String.valueOf(iAssignmentID)); ContentValues event = new ContentValues(); for(int i = 0; i< whereArgs.size(); i++) { Where w = whereArgs.get(i); event.put(w.getParam(), w.getValue()); } return a.getContentResolver().update(updateEventUri, event, null, null); } else throw new HomeworkException(STRING_ASSIGNMENT_NOT_FOUND,Exception_ID.ASSIGNMENT_NOT_FOUND); } else throw new HomeworkException(STRING_CALENDAR_NOT_SET,Exception_ID.CALENDAR_NOT_SELECTED); } /** * returns the last eventID as int */ public int getLastEvent() { String[] projection = new String[] { “_id” }; Cursor managedCursor = a.managedQuery(eventsUri, projection, null, null, null); if (managedCursor.moveToLast()) { return managedCursor.getInt(0); } else return -1; } /** * @return ArrayList as list of calendars available */ public ArrayList getCalendars() { ArrayList calendarList = new ArrayList(); String[] projection = new String[] { “_id”, “name” }; Cursor managedCursor = a.managedQuery(calendars, projection,”selected=1″, null, null); if (managedCursor.getCount() > 0) { int nameColumn = managedCursor.getColumnIndex(”name”); int idColumn = managedCursor.getColumnIndex(”_id”); while (managedCursor.moveToNext()) { calendarList.add(new CalendarListItem(managedCursor.getString(nameColumn),managedCursor.getLong(idColumn))); } } return calendarList; } /** * * @return calendarID as calendar selected */ public long getSelectedCalendar() { return calendarID; } /** * @param newCalendarID as newly selected calendar */ public void setSelectedCalendar(long newCalendarID) { calendarID = newCalendarID; } }
Craig on February 28, 2010 at 12:52 am
First, I REALLY appreciate your tutorial. It made all the difference in the world on my latest app.
Something I’ve found worth mention.. Your tutorial, as it stands, worked great on my Motorola Cliq, but I was getting bug reports from all over, so after a lot of tracking, I figured out that it’s a good practice to also look for the value “name” in addition to “displayName”. “displayName” seems to be optional, so I have my code look for both and go with whatever it finds.
ContentResolver contentResolver = this.getContentResolver();
final Cursor cursor = contentResolver.query(Uri.parse(”content://calendar/calendars”),
(new String[] { “_id”, “displayName”, “name”, “selected” }), null, null, null);
String myDisplayName=”NONE”;
String myCalName=”NONE”;
while (cursor.moveToNext()) {
final String _id = cursor.getString(0);
final String displayName = cursor.getString(1);
final String calName = cursor.getString(2);
final Boolean selected = !cursor.getString(3).equals(”0″);
if (displayName.contains(”gmail.com”)) { useCalId=_id; myDisplayName=displayName; myCalName=calName; }
if (calName.contains(”gmail.com”)) { useCalId=_id; myDisplayName=displayName; myCalName=calName; }
if (selected) { useCalId=_id; myDisplayName=displayName; myCalName=calName; }
if (Debug) { Log.i(”DEBUG”, “totalCals: “+String.valueOf(totalCals)+” CalId: “+String.valueOf(_id)+” Calendar: “+displayName+” CalName: “+calName+” selected: “+String.valueOf(selected)); }
}
And once again, thank you VERY much for getting me off in the right direction!
- Craig
SweetMerch.com
Aleksey on March 5, 2010 at 6:43 am
Jim, echoing everyone here once more; THANKS for the hard work you put into this tutorial.
I’m having some trouble getting your code to run on my Motorola CLIQ (v1.5). I checked out your AndroidReadCalendarExample from your SVN, “tethered” my CLIQ and launched your code. I am getting the following errors from the console though:
[2010-03-05 00:34:51 - AndroidReadCalendarExample]Starting activity net.jimblackler.readcalendar.MainActivity on device
[2010-03-05 00:34:52 - AndroidReadCalendarExample]ActivityManager: Can’t dispatch DDM chunk 46454154: no handler defined
[2010-03-05 00:34:52 - AndroidReadCalendarExample]ActivityManager: Can’t dispatch DDM chunk 4d505251: no handler defined
[2010-03-05 00:34:53 - AndroidReadCalendarExample]ActivityManager: Starting: Intent { comp={net.jimblackler.readcalendar/net.jimblackler.readcalendar.MainActivity} }
These are the last four lines from the console, so somehow it is not reading the calendar correctly.
Thanks in advance,
Aleksey
Kyle on March 16, 2010 at 1:12 pm
John - great helper class, thank you. Although, I was wondering if you could either parse it down a little or provide the rest of the code for it…not having all of the imports makes it a little challenging. Also, what build of the SDK did you use for this?
Thanks
-Kyle
Kyle on March 16, 2010 at 2:59 pm
One other question for John…what is the CalendarListItem class around line 185? Is that something in the SDK or within your project?
- kyle
Rajeev on May 10, 2010 at 5:29 am
Hi Jim,
Many thanks for this forum and it has been extremely useful to me. Thank you.
This would be very useful to me now - Can you provide detailed description on creating a new calendar (and not events) on a device and getting it sync-ed with the google cloud ? What has been your experience with Google api on this front as well ?
many thanks once again,
rajeev
Michael Saunders on May 12, 2010 at 5:20 am
Jim,
Great article. I really appreciate you providing this Calendar example and blog. Has your employer OKed the release of the source code for QuickCalendar yet? It would be really helpful to see the source code of a full application.
Thanks,
Michael
Ken Hughes on May 16, 2010 at 3:09 pm
Great article. Been wanting an app to turn off my phone ringer when in certain meetings, now I can write one.
Jeffrey Karp on May 16, 2010 at 4:15 pm
My HTC Eris did an update today to 2.1 - I didn’t have a backup of my calendar but I see that my calendar storage has 13.5 MB so I assume my data is still there - is there a way for me to access this?
Jeffrey Karp on May 16, 2010 at 4:16 pm
meant to add that I can’t access my calendar…
John on May 18, 2010 at 3:48 am
Hey Kyle, I’ve worked with that piece of code quite a bit since I originally posted on here.
CalendarEventItem was just a small class to hold the name of a calendar and it’s id.
That is the entire class, and I cannot at this time post any more of the project.
However, I can post a few examples of how it is used if you want although it’s pretty self explanatory.
1 Thing I cannot figure out though is how to get a reminder to be used. I just can’t get it to use a reminder =[
Tim on May 25, 2010 at 6:19 pm
Hi Jim, thanks for the article. I used it when I was researching my own calendar widget app. Unfortunately, it looks like the Froyo release has changed the URI we need. Do you or does anyone else know what changes are needed to get our apps to work on Froyo?
moamen on June 3, 2010 at 3:36 am
hello Jim, please provide us with help for froyo calendar
i’m working in my app for my nexus one to add events to calendar but from now i don’t know how to move forward
thanks for your help and wish we receive more
moamen on June 4, 2010 at 5:30 pm
i can provide you with the calendar 2.2 from my phone in case it will help
Content provider URI
Old: content://calendar/
New: content://com.android.calendar/
good luck
moamen on June 12, 2010 at 9:38 pm
now i can write event to the froyo calendar, my problem is adding reminder to it
i can add reminder to it by using the content://com.android.calendar/reminders but i don’t know why it’s not working and on the first sync the reminder got removed.
i tried to use calendarAlerts but didn’t work
please help
John on June 14, 2010 at 7:58 am
static String contentProvider;
static Uri remindersUri;
static Uri eventsUri;
static Uri calendars;
if(Build.VERSION.RELEASE.contains(”2.2″))
contentProvider = “com.android.calendar”;
else
contentProvider = “calendar”;
remindersUri = Uri.parse(String.format(”content://%s/reminders”,contentProvider));
eventsUri = Uri.parse(String.format(”content://%s/events”,contentProvider));
calendars = Uri.parse(String.format(”content://%s/calendars”,contentProvider));
Surya Gopal on June 28, 2010 at 7:17 am
HI,
I have gone through your blog about android examples. its very nice, and more understandable format.
I am new to android, iam working rit now on android, plz help me how to connect to sqlite and access the data, and update, plz help me with small example.
moamen on June 30, 2010 at 11:56 pm
can any one help me to understand this.
the reminder table has a column called method, its allowed values are 0,1,2,3
0 for default and do nothing
1 add reminder
2 email reminder
3 SMS
in case of email and SMS where the number of the SMS recipient can be saved?
if any one know please help
moamen on June 30, 2010 at 11:57 pm
Surya Gopal, send me your email and i’ll send u a class to access DB
cad13 on July 9, 2010 at 12:49 am
Hi Jim,
Thanks for this tuto.
Do you know how to proceed for deleting events between 2 dates ?
I tried to use the second part of your code (which display all events between 2 dates), but how to delete them instead of displaying them ?
I also tried using
Uri url = getContentResolver().delete(eventsUri, event)
but how to parse the events from date to date ?
Thank you if you can help…
Christian
Domenok on July 12, 2010 at 9:49 pm
can u give me more detailes please? Thanks
cad13 on July 16, 2010 at 5:48 pm
Ok I can parse my events using your example, but unfortunately, I cannot delete any of them !
Do you have an idea for that ?
I tried :
Uri eventsUri = Uri.parse(uriCal + “/events”);
Uri uri = ContentUris.withAppendedId(eventsUri, eventid);
int nb = contentResolver.delete(uri, null , null);
or this :
Uri eventsUri = Uri.parse(uriCal + “/events”);
int nb = contentResolver.delete(eventsUri, “_id=”+id, null);
But nothing happens, my events are still there !
cad13 on July 19, 2010 at 2:42 pm
Solution : use “event_id=” instead of “_id=”
David Cheney on July 28, 2010 at 2:16 am
Thank you thank you thank you …
bender on August 12, 2010 at 4:28 pm
Thanks for this great article!
There is something that confuses me about this and another tutorial which I found here: http://www.developer.com/ws/article.php/3850276/Working-with-the-Android-Calendar.htm
In this tutorial you get the start and end times of an event in the query via “begin” and “end”.
In the other tutorial is explained how to submit a new event to the calendar, and the start and endtimes there are put with:
event.put(”dtstart”, startTime);
event.put(”dtend”, endTime);
I tried to insert a new event and replaced “dtstart” with “begin” and “dtend” with “end” but received an exception that I need to put a value for “dtstart”.
So my question is, why do you use “begin” to get the time when retrieving an event and “dtstart” when inserting a new one? Aren’t these the column names of the calendars db?
Mark on August 30, 2010 at 1:55 am
Has anybody been able to figure out what the calendar provider URI is for HTC SenseUI phones such as the Hero, Incredible and Desire? The code on this site crashes with an unknown URI error when I try to run it on any of those phones.
PB on September 11, 2010 at 11:30 am
hey, ur post is very good.. m trying to parse xml data in my application from a site.. can u help me wid some code..
Thanks
Kapuddi on October 4, 2010 at 5:51 pm
Hi, Jim.
When I insert one new Calendar Event into Google calendar from my app,
the fail log message was given:
10-05 00:30:44.171: ERROR/DatabaseUtils(8479): Error inserting transparency=0 dtstart=1285891200000 title=TestCalendar _sync_dirty=1 dtend=1285891200000 visibility=0 allDay=1 lastDate=1285950628697 hasAlarm=0 eventStatus=1 into table Events
10-05 00:30:44.171: ERROR/DatabaseUtils(8479): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
10-05 00:30:44.171: ERROR/DatabaseUtils(8479): at android.database.sqlite.SQLiteStatement.native_execute(Native Method)
Can you give me some advice?
Next is the sample code:
================================================================================
ContentValues event = new ContentValues();
//event.put(”title”, mAct.getString(R.string.read) + “: ” + title);
event.put(Events.TITLE, “TestCalendar”);
long startTime = startC.getTimeInMillis();
long endTime = endC.getTimeInMillis();
event.put(Events.DTSTART, startTime);
event.put(Events.DTEND, endTime);
event.put(Events.ALL_DAY, 1);
event.put(Events.STATUS, Events.STATUS_CONFIRMED);
event.put(Events.VISIBILITY, Events.VISIBILITY_DEFAULT);
event.put(Events.TRANSPARENCY, Events.TRANSPARENCY_OPAQUE);
event.put(Events.HAS_ALARM, 0);
if (resetTag) {
mAct.getContentResolver().update(Events.CONTENT_URI, event, Events._ID + “=” + contentId, null);
return contentId;
}else {
Uri uri = mAct.getContentResolver().insert(Events.CONTENT_URI, event);
return ContentUris.parseId(uri);
}
Rusty on October 16, 2010 at 7:06 pm
Hi Jim, thanks for the post. I have found it very useful to get me going with the calendars.
For any others - I’m using HTC Desire with Android 2.2 (Froyo) and this URI content://com.android.calendar
Cheers,
Rusty
cow on October 26, 2010 at 9:05 am
Hi,
Can anyone tell me how to get the last modification time of the event?
Thanks
David on October 26, 2010 at 6:54 pm
Hi Jim,
Thank you for posting your article.
Can you give me a tip how to replace android.provider.Calendar in the Google source code? Where can I find the @hide files?
Thank you.
David
Talha on October 27, 2010 at 7:48 am
Hi there,
can anyone tell me if there is a way to query through code if there is a calendar available on the device. As far as I know there are two calendars, google and corporate??? or is it that we can only get this info through cursor???
Secondly, I have noticed that if there is another application using the calendar, my app fails to connect to calendar…
Like the code that Jim Blackler has written to connect to calendar:
final Cursor cursor = contentResolver.query(Uri.parse(”content://calendar/calendars”),
(new String[] { “_id”, “displayName”, “selected” }), null, null, null);
Are there any known exceptions to this method or return values from which one could get to know what exactly failed the cursor from opening???
thanx
jimblackler on October 27, 2010 at 10:36 am
Hi Pierrot, Corporate (on Motorola devices) has a different provider, I believe there is a note in the article.
Shimon Shnitzer on November 2, 2010 at 1:03 pm
Hi,
When using the code you gave here to launch the event ACTION_EDIT intent, can I somehow set the default calendar selected for the event ?
What used to work in the past was I created an event in my code (using the .insert function, the launched the intent ACTION_EDIT with intent.setDate().
This then displayed the event edit dialog with the calendar_id I used to create the event in code set.
Now the dialog does open, but it selected the first calendar by default, so if I press the Done button - I get TWO events - one that I created in code with my desired calendar, and another one created by the EDIT dialog - in the first calendar.
Am I making any sense here ?
Any solution ?
TIA
Paresh on November 29, 2010 at 10:33 am
Hello, i have referred your article, really its AWESOME,
but one think i want to know about the Calendar events, How do i fetch events for the particular date only ??
please please let me know !!
Awais on January 18, 2011 at 5:07 pm
01-18 20:45:33.589: ERROR/ActivityThread(472): Failed to find provider info for calendar
can anyone help. I guess my emulater don’t have any calendar installed yet. How to do it?
Help Jim, Please drop mail.
Will be grateful
thanks
Frankie on January 22, 2011 at 8:08 am
My Final Year Project is building with android apps and i want to add a calender function on it. it ’s so useful for me but my emulator don’t have any calendar installed yet.
Could u mind to help me to solve this problem?
thank for so much !!!!!!