On my LG-G3 there is a default calendar named "Phone". It's not Google's.
I build an application which syncs events with the user's Google Calendars, but when I select all the calendars with a query - I get the "Phone" calendar too. Since it's not a Google calendar, I can't use it with the Google Calendar functions (insert, delete, etc.).
I can't see any different between "Phone" calendar and Google canledars except of its name. Is there any way to know if a calendar is Google's or not?
This is my query:
String[] l_projection = new String[] { Calendars._ID, Calendars.CALENDAR_DISPLAY_NAME, Calendars.CALENDAR_ACCESS_LEVEL, Calendars.ALLOWED_REMINDERS, Calendars.SYNC_EVENTS };
Uri l_calendars;
if (Build.VERSION.SDK_INT >= 8) {
l_calendars = Uri.parse("content://com.android.calendar/calendars");
} else {
l_calendars = Uri.parse("content://calendar/calendars");
}
try {
Cursor l_managedCursor = activity.getContentResolver().query(l_calendars, l_projection, null, null, null);
if (l_managedCursor.moveToFirst()) {
String l_methodAllow;
String l_accessPermission;
String l_calName;
String l_calId;
String l_syncEvents;
int l_cnt = 0;
int l_syncEventsCol = l_managedCursor.getColumnIndex(l_projection[4]);
int l_methodAllowCol = l_managedCursor.getColumnIndex(l_projection[3]);
int l_accessPermissionCol = l_managedCursor.getColumnIndex(l_projection[2]);
int l_nameCol = l_managedCursor.getColumnIndex(l_projection[1]);
int l_idCol = l_managedCursor.getColumnIndex(l_projection[0]);
do {
String access = l_managedCursor.getString(l_accessPermissionCol);
if (access.equals("500") || access.equals("600") || access.equals("700") || access.equals("800")) {
l_syncEvents = l_managedCursor.getString(l_syncEventsCol);
l_methodAllow = l_managedCursor.getString(l_methodAllowCol);
l_accessPermission = l_managedCursor.getString(l_accessPermissionCol);
l_calName = l_managedCursor.getString(l_nameCol);
l_calId = l_managedCursor.getString(l_idCol);
calNames.add(l_calName);
// ....
++l_cnt;
}
} while (l_managedCursor.moveToNext());
}
} catch (Exception e) {
// ...
}
Google calendar can be identified by looking at the domain name of the Calendar ID. For primary calendar, calendar ID domain name is #gmail.com. If its secondary calendar, calendar ID domain name is group.calendar.google.com
Related
I currently have a feature in my app that inserts an event into Google Calendar. However, the code for this feature is over 4 years old and today, when I tested this app, I saw that the event is not being inserted into Google Calendar. However, it is on the normal Android calendar, but when I access my Google account, the event you created is not listed.
The code that performs such insertion is this:
public class CalendarEventCreator
{
private String userAccount,timeZone,accountName,displayName;
private long calendarID;
private boolean haveMainCalendar;
/*
* Columns of the Calendar's table
* */
private static final String[] COLUMNS = new String[]
{
Calendars._ID, // 0
Calendars.ACCOUNT_NAME, // 1
Calendars.CALENDAR_DISPLAY_NAME, // 2
Calendars.OWNER_ACCOUNT, // 3
Calendars.CALENDAR_TIME_ZONE // 4
};
private void initializer()
{
haveMainCalendar = false;
userAccount = null;
accountName = null;
displayName = null;
timeZone = null;
calendarID =-1;
}
/*
* Search for the first gmail account
* TODO:support multiple google accounts on the same device
* */
private void getUserMainCalendar(Context ctx)
{
ContentResolver cr = ctx.getContentResolver();
initializer();
Cursor cur = null;
cur = cr.query(Calendars.CONTENT_URI, COLUMNS,null,null,null);
while(cur.moveToNext())
{
if (cur.getString(3).contains("#gmail.com"))
{
haveMainCalendar = true;
calendarID = cur.getLong(0);
accountName = cur.getString(1);
displayName = cur.getString(2);
userAccount = cur.getString(3);
timeZone = cur.getString(4);
break;
}
}
}
public void addEventCalendar(Reminder reminder, Context ctx) throws CalendarNotFoundException,
ParseException
{
long startMilliseconds,endmilliseconds;
Calendar calEnd;
startMilliseconds = endmilliseconds = 0;
getUserMainCalendar(ctx);
if(haveMainCalendar)
{
ContentResolver cr = ctx.getContentResolver();
calEnd = Calendar.getInstance();
Date date = DateFormat.dateFormater(reminder.getDate()+" "+reminder.getHour());
calEnd.setTime(date);
startMilliseconds = calEnd.getTimeInMillis()-100000;
endmilliseconds = calEnd.getTimeInMillis();
ContentValues values = new ContentValues();
values.put(Events.DTSTART,startMilliseconds);
values.put(Events.DTEND,endmilliseconds);
values.put(Events.TITLE,reminder.getText());
values.put(Events.DESCRIPTION,reminder.getCategory().getName()+" - PositivoApp");
values.put(Events.CALENDAR_ID,calendarID);
values.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
cr.insert(Events.CONTENT_URI, values);
}
else
throw new CalendarNotFoundException();
}
}
The SKD version is:
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="16" />
Is there anything wrong with this code?
set your OAuth scope to https://www.googleapis.com/auth/calendar.
ensure the authenticated user has write access to the calendar with the calendarId you provided (for example by calling calendarList.get() for the calendarId and checking the accessRole).
There is a java sample on Events.insert which shows how to add events:
// Refer to the Java quickstart on how to setup the environment:
// https://developers.google.com/calendar/quickstart/java
// Change the scope to CalendarScopes.CALENDAR and delete any stored
// credentials.
Event event = new Event()
.setSummary("Google I/O 2015")
.setLocation("800 Howard St., San Francisco, CA 94103")
.setDescription("A chance to hear more about Google's developer products.");
DateTime startDateTime = new DateTime("2015-05-28T09:00:00-07:00");
EventDateTime start = new EventDateTime()
.setDateTime(startDateTime)
.setTimeZone("America/Los_Angeles");
event.setStart(start);
DateTime endDateTime = new DateTime("2015-05-28T17:00:00-07:00");
EventDateTime end = new EventDateTime()
.setDateTime(endDateTime)
.setTimeZone("America/Los_Angeles");
event.setEnd(end);
String[] recurrence = new String[] {"RRULE:FREQ=DAILY;COUNT=2"};
event.setRecurrence(Arrays.asList(recurrence));
EventAttendee[] attendees = new EventAttendee[] {
new EventAttendee().setEmail("lpage#example.com"),
new EventAttendee().setEmail("sbrin#example.com"),
};
event.setAttendees(Arrays.asList(attendees));
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 = service.events().insert(calendarId, event).execute();
System.out.printf("Event created: %s\n", event.getHtmlLink());
Don't forget to set your scope to https://www.googleapis.com/auth/calendar as have been mentioned. If you're changing scopes, delete the previously saved .json credentials for the new scope to take effect.
I'm trying to create a calendar on google account, I managed to create calendars but none syncs with google and I don't know what I'm doing wrong.
I know where the problem more or less but I can't fix it.
The code I use is this:
public static long createCalendar (Activity activity, String name, String account, boolean local){
String color = "blue";
ContentValues calendarvalues = new ContentValues();
//The account that was used to sync the entry to the device. If the account_type is not {#link #ACCOUNT_TYPE_LOCAL} then the name and
// type must match an account on the device or the calendar will be deleted.
if(local) {
calendarvalues.put(CalendarContract.Calendars.ACCOUNT_NAME, "DUMMYLOCAL");
calendarvalues.put(CalendarContract.Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL);
}else{
calendarvalues.put(CalendarContract.Calendars.ACCOUNT_NAME, account);
calendarvalues.put(CalendarContract.Calendars.ACCOUNT_TYPE, account);
}
//Local CalendarContract.ACCOUNT_TYPE_LOCAL
calendarvalues.put(CalendarContract.Calendars.NAME, name);
calendarvalues.put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, name);
calendarvalues.put(CalendarContract.Calendars.CALENDAR_COLOR, Color.parseColor(color));
calendarvalues.put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_OWNER);
// //None CalendarContract.Calendars.CAL_ACCESS_NONE Cannot access the calendar
// //freeBusy CalendarContract.Calendars.CAL_ACCESS_FREEBUSY Can only see free/busy information about the calendar
// //Read CalendarContract.Calendars.CAL_ACCESS_READ Can read all event details
// //Respond CalendarContract.Calendars.CAL_ACCESS_RESPOND Can reply yes/no/maybe to an event
// //Override CalendarContract.Calendars.CAL_ACCESS_OVERRIDE not used
// //Contributor CalendarContract.Calendars.CAL_ACCESS_CONTRIBUTOR Full access to modify the calendar, but not the access control settings
// //Editor CalendarContract.Calendars.CAL_ACCESS_EDITOR Full access to modify the calendar, but not the access control settings
// //Owner CalendarContract.Calendars.CAL_ACCESS_OWNER Full access to the calendar
// //Root CalendarContract.Calendars.CAL_ACCESS_ROOT Domain admin
calendarvalues.put(CalendarContract.Calendars.OWNER_ACCOUNT, account);
calendarvalues.put(CalendarContract.Calendars.VISIBLE, 1);
calendarvalues.put(CalendarContract.Calendars.SYNC_EVENTS, 1);
// calendarvalues.put(CalendarContract.Calendars.CALENDAR_LOCATION, "Spain");
Uri calUri = null;
Uri result = null;
if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
PermissionUtil.requestCalendarPermission(activity);
return -1;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
calUri = CalendarContract.Calendars.CONTENT_URI;
}else{
calUri = Uri.parse("content://com.android.calendar/calendars");
}
if(calUri != null) {
if(local) {
calUri = calUri.buildUpon()
.appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, "DUMMYLOCAL")
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL)
.build();
}else {
calUri = calUri.buildUpon()
.appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, account)
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, account)
.build();
}
result = activity.getContentResolver().insert(calUri, calendarvalues);
}
if (result != null) {
try {
return Long.parseLong(result.getLastPathSegment());
} catch (Exception e) {
return -1;
}
}
return -1;
}
I think the mistake is in this line :
calendarvalues.put(CalendarContract.Calendars.ACCOUNT_TYPE, account);
because I have seen the values returned by the following query:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
calUri = CalendarContract.Calendars.CONTENT_URI;
}else{
calUri = Uri.parse(calendarUriString);
}
String[] projection = new String[]{
CalendarContract.Calendars._ID,
CalendarContract.Calendars.NAME,
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL,
CalendarContract.Calendars.ACCOUNT_NAME,
CalendarContract.Calendars.ACCOUNT_TYPE,
// CalendarContract.Calendars.CALENDAR_COLOR,
CalendarContract.Calendars.OWNER_ACCOUNT,
CalendarContract.Calendars.VISIBLE,
CalendarContract.Calendars.SYNC_EVENTS,
};
Cursor cursor = activity.getContentResolver().query(calUri, projection, null, null, null);
and the results are as follows:
id: 1
Name: My Calendar#Local
Display name: My Calendar
access level: 700
AccountName: My Calendar#Local
AccountType: com.local
ownerAccount: Owner Account visible: 1
sync: 1
id: 2
Name: test#gmail.com
Display name: test#gmail.com
access level: 700
AccountName: test#gmail.com
AccountType: com.google
ownerAccount: test#gmail.com
visible: 1
sync: 1
id: 3
Name: Test Cal
Display name: Test Cal
access level: 700
AccountName: test#gmail.com
AccountType: test#gmail.com
ownerAccount: 1
visible: 1
sync: 1
I tried to put the following:
calendarvalues.put(CalendarContract.Calendars.ACCOUNT_TYPE, "com.google");
but the calendar is not created.
If anyone knows how to do it or have any examples or documentation that may be useful, it would be helpful.
Thanks in advance.
I was struggling with the same Problem - I ended up creating a calendar using the Google Calendar API insert function. With the Quickstart Guide you should be able to create a Calendar.
Use the MakeRequestTask#mService like this:
Calendar newCalendar = new Calendar();
newCalendar.setSummary("Calendar Name");
newCalendar.setTimeZone(TIME_ZONE); //assuming you have it as a constant somewhere
String newCalendarId = null;
try {
com.google.api.services.calendar.model.Calendar insertedCalendar = mService.calendars().insert(newCalendar).execute();
newCalendarId = insertedCalendar.getId();
} catch(Exception ignore){}
and then force an account sync with
Bundle extras = new Bundle();
extras.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
ContentResolver.requestSync(selectedAccount, CalendarContract.AUTHORITY, extras);
I am doing backup and restore of calendars, During restore if calendar is not present in phone(but related account is present), i am creating new calendar with the following code, it has successfully inserted into db (i can see the return value of URI and id). But in calendar application it is visible for an second and disappears,i have no clue what is going wrong, i have made the visible flag with 1 on insertion but still not working.Can someone Help.
final String INT_NAME_PREFIX = "priv";
Uri calUri = CalendarContract.Calendars.CONTENT_URI
.buildUpon()
.appendQueryParameter(
CalendarContract.CALLER_IS_SYNCADAPTER, "true")
.appendQueryParameter(Calendars.ACCOUNT_NAME,
mCurrentMirrorItem.ACCOUNT_NAME)
.appendQueryParameter(Calendars.ACCOUNT_TYPE,
mCurrentMirrorItem.ACCOUNT_TYPE).build();
String dispName = mItem.CALENDAR_DISPLAY_NAME;
String intName = INT_NAME_PREFIX + dispName;
ContentValues contentValues = new ContentValues();
if (columnNames.contains(Calendars.ACCOUNT_NAME)) {
contentValues.put(CalendarContract.Calendars.ACCOUNT_NAME,
mItem.ACCOUNT_NAME);
}
if (columnNames.contains(Calendars.ACCOUNT_TYPE)) {
contentValues.put(CalendarContract.Calendars.ACCOUNT_TYPE,
mItem.ACCOUNT_TYPE);
}
if (columnNames.contains(Calendars.NAME)) {
contentValues.put(CalendarContract.Calendars.NAME, intName);
}
if (columnNames.contains(Calendars.CALENDAR_DISPLAY_NAME)) {
contentValues.put(
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
mItem.CALENDAR_DISPLAY_NAME);
}
if (columnNames.contains(Calendars.CALENDAR_COLOR)) {
contentValues.put(CalendarContract.Calendars.CALENDAR_COLOR,
mItem.CALENDAR_COLOR);
}
if (columnNames.contains(Calendars.CALENDAR_ACCESS_LEVEL)) {
contentValues.put(
CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL,
Calendars.CAL_ACCESS_OWNER);
}
if (columnNames.contains(Calendars.OWNER_ACCOUNT)) {
contentValues.put(CalendarContract.Calendars.OWNER_ACCOUNT,
mItem.ACCOUNT_NAME);
}
if (columnNames.contains(Calendars.VISIBLE)) {
contentValues.put(CalendarContract.Calendars.VISIBLE, 1);
}
if (columnNames.contains(Calendars.SYNC_EVENTS)) {
contentValues.put(CalendarContract.Calendars.SYNC_EVENTS, 1);
}
returnUri = cr.insert(calUri, contentValues);
long eventID = Long.parseLong(returnUri.getLastPathSegment());
calid = String.valueOf(eventID);
Log.d(tag,"calendar name: "+mItem.CALENDAR_DISPLAY_NAME+"\tNew calendar id is: "+calid+"\nInserted URI: "+returnUri);
I'm making a basic Dashclock extension that polls CalendarContract.Events for a list of all calendar events synced to the user's device, retrieve the one that's scheduled to happen the soonest, and post the time, title, location, and desctiption. Here's my code:
public class FullCalService extends DashClockExtension {
public static final String[] FIELDS = { Events._ID, Events.TITLE,
Events.ALL_DAY, Events.EVENT_LOCATION, Events.DTSTART,
Events.EVENT_TIMEZONE, Events.DESCRIPTION };
public FullCalService() {
}
#Override
protected void onUpdateData(int arg0) {
TimeZone tz = TimeZone.getDefault();
long currentTimeMillis = Calendar.getInstance().getTimeInMillis() - tz.getRawOffset();
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
Cursor c;
if (prefs.getBoolean("allDayAllowed", false)) {
c = getContentResolver().query(
Events.CONTENT_URI,
FIELDS,
new StringBuilder().append("(").append(Events.DTSTART)
.append(" >= ?)").toString(),
new String[] { Long.toString(currentTimeMillis) },
Events.DTSTART, null);
} else {
c = getContentResolver().query(
Events.CONTENT_URI,
FIELDS,
new StringBuilder().append("((").append(Events.ALL_DAY)
.append("= ?) AND (").append(Events.DTSTART)
.append(" >= ?))").toString(),
new String[] { Integer.toString(0),
Long.toString(currentTimeMillis) }, Events.DTSTART,
null);
}
if (c.moveToFirst()) {
long eventTimeMillis = c.getLong(c.getColumnIndex(Events.DTSTART));
// if (tz.inDaylightTime(new Date(eventTimeMillis))) {
// eventTimeMillis += tz.getDSTSavings();
// }
//Log.d("DesCal service", "Value of hoursToReveal: "+prefs.getString("hoursToReveal", "1"));
if (eventTimeMillis < currentTimeMillis + 360000
* Integer.parseInt(prefs.getString("hoursToReveal", "1"))) {
String title = c.getString(c.getColumnIndex(Events.TITLE));
String loc = c.getString(c
.getColumnIndex(Events.EVENT_LOCATION));
String time = DateUtils.formatDateTime(this, eventTimeMillis,
DateUtils.FORMAT_SHOW_TIME);
String desc = c.getString(c.getColumnIndex(Events.DESCRIPTION));
StringBuilder expandedBody = new StringBuilder(time);
if (!loc.isEmpty()){
expandedBody.append(" - ").append(loc);
}
expandedBody.append("\n").append(desc);
String uri = new StringBuilder(
"content://com.android.calendar/events/").append(
c.getLong(c.getColumnIndex(Events._ID))).toString();
publishUpdate(new ExtensionData()
.visible(true)
.status(time)
.expandedTitle(title)
.expandedBody(expandedBody.toString())
.icon(R.drawable.ic_dash_cal)
.clickIntent(
new Intent(Intent.ACTION_VIEW, Uri.parse(uri))));
c.close();
} else {
publishUpdate(new ExtensionData().visible(false));
c.close();
}
} else {
publishUpdate(new ExtensionData().visible(false));
c.close();
}
}
}
Upon first install, it appeared to work just fine. However, after the event began, it would not grab any future events. Is there a reason why the extension will not refresh itself?
How are you triggering further updates? You need to manually specify when you'd like to have onUpdateData called, e.g. when there's a change to a content provider, or when the screen turns on, etc. Extensions by default refresh only every 30 minutes or so. See the source for the built in calendar extension for example code.
My issue is, I have to make one demo application in which I wants to read the events of the Google calendar, for that I have manually inserted the events like the title of event, the time of events and the details of the whole events. now I need to just read those events form that calendar.
For that I have tried to use the gcode(google code) API which provides the calendar API class. But still I cant read those events.
That code above is pretty awful (and it does not seem to work in ICS - definitely the column names are different)
The page here:
http://developer.android.com/guide/topics/providers/calendar-provider.html
provides a much better overview.
A (much) simpler code to retrieve calendars:
public class CalendarContentResolver {
public static final String[] FIELDS = {
CalendarContract.Calendars.NAME,
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
CalendarContract.Calendars.CALENDAR_COLOR,
CalendarContract.Calendars.VISIBLE
};
public static final Uri CALENDAR_URI = Uri.parse("content://com.android.calendar/calendars");
ContentResolver contentResolver;
Set<String> calendars = new HashSet<String>();
public CalendarContentResolver(Context ctx) {
contentResolver = ctx.getContentResolver();
}
public Set<String> getCalendars() {
// Fetch a list of all calendars sync'd with the device and their display names
Cursor cursor = contentResolver.query(CALENDAR_URI, FIELDS, null, null, null);
try {
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String name = cursor.getString(0);
String displayName = cursor.getString(1);
// This is actually a better pattern:
String color = cursor.getString(cursor.getColumnIndex(CalendarContract.Calendars.CALENDAR_COLOR));
Boolean selected = !cursor.getString(3).equals("0");
calendars.add(displayName);
}
}
} catch (AssertionError ex) { /*TODO: log exception and bail*/ }
return calendars;
}
}
Hope this helps!
Ok i found the answer of this whole of the concept that how to use the google calendar application integration with the android phone.
code:--
first you set this line which will goes to read the calendar events form the other class form your class which is current is the ApplicationSettings.java .
ReadCalendar.readCalendar(ApplicationSettings.this);
package com.mycalendarevents.android;
import java.util.Date;
import java.util.HashSet;
import java.util.regex.Pattern;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.text.format.DateUtils;
public class ReadCalendar
{
static Cursor cursor;
public static void readCalendar(Context context) {
ContentResolver contentResolver = context.getContentResolver();
// Fetch a list of all calendars synced with the device, their display names and whether the
cursor = contentResolver.query(Uri.parse("content://com.android.calendar/calendars"),
(new String[] { "_id", "displayName", "selected"}), null, null, null);
HashSet<String> calendarIds = new HashSet<String>();
try
{
System.out.println("Count="+cursor.getCount());
if(cursor.getCount() > 0)
{
System.out.println("the control is just inside of the cursor.count loop");
while (cursor.moveToNext()) {
String _id = cursor.getString(0);
String displayName = cursor.getString(1);
Boolean selected = !cursor.getString(2).equals("0");
System.out.println("Id: " + _id + " Display Name: " + displayName + " Selected: " + selected);
calendarIds.add(_id);
}
}
}
catch(AssertionError ex)
{
ex.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
// For each calendar, display all the events from the previous week to the end of next week.
for (String id : calendarIds) {
Uri.Builder builder = Uri.parse("content://com.android.calendar/instances/when").buildUpon();
//Uri.Builder builder = Uri.parse("content://com.android.calendar/calendars").buildUpon();
long now = new Date().getTime();
ContentUris.appendId(builder, now - DateUtils.DAY_IN_MILLIS * 10000);
ContentUris.appendId(builder, now + DateUtils.DAY_IN_MILLIS * 10000);
Cursor eventCursor = contentResolver.query(builder.build(),
new String[] { "title", "begin", "end", "allDay"}, "Calendars._id=" + 1,
null, "startDay ASC, startMinute ASC");
System.out.println("eventCursor count="+eventCursor.getCount());
if(eventCursor.getCount()>0)
{
if(eventCursor.moveToFirst())
{
do
{
Object mbeg_date,beg_date,beg_time,end_date,end_time;
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);
*/
System.out.println("Title:"+title);
System.out.println("Begin:"+begin);
System.out.println("End:"+end);
System.out.println("All Day:"+allDay);
/* the calendar control metting-begin events Respose sub-string (starts....hare) */
Pattern p = Pattern.compile(" ");
String[] items = p.split(begin.toString());
String scalendar_metting_beginday,scalendar_metting_beginmonth,scalendar_metting_beginyear,scalendar_metting_begindate,scalendar_metting_begintime,scalendar_metting_begingmt;
scalendar_metting_beginday = items[0];
scalendar_metting_beginmonth = items[1];
scalendar_metting_begindate = items[2];
scalendar_metting_begintime = items[3];
scalendar_metting_begingmt = items[4];
scalendar_metting_beginyear = items[5];
String calendar_metting_beginday = scalendar_metting_beginday;
String calendar_metting_beginmonth = scalendar_metting_beginmonth.toString().trim();
int calendar_metting_begindate = Integer.parseInt(scalendar_metting_begindate.trim());
String calendar_metting_begintime = scalendar_metting_begintime.toString().trim();
String calendar_metting_begingmt = scalendar_metting_begingmt;
int calendar_metting_beginyear = Integer.parseInt(scalendar_metting_beginyear.trim());
System.out.println("calendar_metting_beginday="+calendar_metting_beginday);
System.out.println("calendar_metting_beginmonth ="+calendar_metting_beginmonth);
System.out.println("calendar_metting_begindate ="+calendar_metting_begindate);
System.out.println("calendar_metting_begintime="+calendar_metting_begintime);
System.out.println("calendar_metting_begingmt ="+calendar_metting_begingmt);
System.out.println("calendar_metting_beginyear ="+calendar_metting_beginyear);
/* the calendar control metting-begin events Respose sub-string (starts....ends) */
/* the calendar control metting-end events Respose sub-string (starts....hare) */
Pattern p1 = Pattern.compile(" ");
String[] enditems = p.split(end.toString());
String scalendar_metting_endday,scalendar_metting_endmonth,scalendar_metting_endyear,scalendar_metting_enddate,scalendar_metting_endtime,scalendar_metting_endgmt;
scalendar_metting_endday = enditems[0];
scalendar_metting_endmonth = enditems[1];
scalendar_metting_enddate = enditems[2];
scalendar_metting_endtime = enditems[3];
scalendar_metting_endgmt = enditems[4];
scalendar_metting_endyear = enditems[5];
String calendar_metting_endday = scalendar_metting_endday;
String calendar_metting_endmonth = scalendar_metting_endmonth.toString().trim();
int calendar_metting_enddate = Integer.parseInt(scalendar_metting_enddate.trim());
String calendar_metting_endtime = scalendar_metting_endtime.toString().trim();
String calendar_metting_endgmt = scalendar_metting_endgmt;
int calendar_metting_endyear = Integer.parseInt(scalendar_metting_endyear.trim());
System.out.println("calendar_metting_beginday="+calendar_metting_endday);
System.out.println("calendar_metting_beginmonth ="+calendar_metting_endmonth);
System.out.println("calendar_metting_begindate ="+calendar_metting_enddate);
System.out.println("calendar_metting_begintime="+calendar_metting_endtime);
System.out.println("calendar_metting_begingmt ="+calendar_metting_endgmt);
System.out.println("calendar_metting_beginyear ="+calendar_metting_endyear);
/* the calendar control metting-end events Respose sub-string (starts....ends) */
System.out.println("only date begin of events="+begin.getDate());
System.out.println("only begin time of events="+begin.getHours() + ":" +begin.getMinutes() + ":" +begin.getSeconds());
System.out.println("only date begin of events="+end.getDate());
System.out.println("only begin time of events="+end.getHours() + ":" +end.getMinutes() + ":" +end.getSeconds());
beg_date = begin.getDate();
mbeg_date = begin.getDate()+"/"+calendar_metting_beginmonth+"/"+calendar_metting_beginyear;
beg_time = begin.getHours();
System.out.println("the vaule of mbeg_date="+mbeg_date.toString().trim());
end_date = end.getDate();
end_time = end.getHours();
CallHandlerUI.metting_begin_date.add(beg_date.toString());
CallHandlerUI.metting_begin_mdate.add(mbeg_date.toString());
CallHandlerUI.metting_begin_mtime.add(calendar_metting_begintime.toString());
CallHandlerUI.metting_end_date.add(end_date.toString());
CallHandlerUI.metting_end_time.add(end_time.toString());
CallHandlerUI.metting_end_mtime.add(calendar_metting_endtime.toString());
}
while(eventCursor.moveToNext());
}
}
break;
}
}
}
here is the whole of the code is to be posted which will simply reads each and every events form your calendar with the help of that postback url which is for 2.2 and above version:
Uri.parse("content://com.android.calendar/instances/when").buildUpon();
pl find the under those version lower then 2.2 in android and use those events as you required place...
I am aware that this is an old post, but I found inspiration for optimizing the solution found in the answer given by Akash Takkar if anyone is in need of a solution in the near future.
The issues
Specically, I found a few issues in the original code:
The loop for retrieving calendar events broke immaturely
Hereby, only events from the first calendar was retrieved
The first event in each calendar was skipped by using eventCursor.moveToFirst(); which thereafter moves directly to the next event in the while loop
The id of the calendars were not set correctly in the eventCursor
"Calendars._id=" + 1, should be "Calendars._id=" + id,
It would be difficult for others to specify their own time range
The current solution is not object oriented which would hold many advantages
The readability and documentation is not the best
The solution
I have hereby created a Github Library which returns a list of event objects in a specified time range which can be found at:
https://github.com/david-laundav/CalendarService
The source files can be found under "CalendarService/src/dk/CalendarService".
Use cases
The solution itself contains two different methods for different purposes.
First use case:
CalendarService.readCalendar(class.this)
// where class.this is either your class or the context
This method will return a list of events for +/- 1 day
Second use case:
You can also specify your own time range:
CalendarService.readCalendar(class.this, int days, int hours)
An example might be:
CalendarService.readCalendar(class.this, 2, 5)
In doing so will return a list of events from +/-2 days and +/- 5 hours.
The service has been tested, but please tell me if you experience any issues.
This post is a little bit old, but here is another easy solution for getting data related to Calendar content provider in Android:
Use this lib: https://github.com/EverythingMe/easy-content-providers
And now, get all calendars:
CalendarProvider calendarProvider = new CalendarProvider(context);
List<Calendar> calendars = calendarProvider.getCalendars().getList();
Each Calendar has all fields, so you can get any info you need:
id, name, calendarColor, ownerAccount, accountName, calendarAccessLevel, ...
Or, get all Events of specific calendar:
List<Event> calendars = calendarProvider.getEvents(calendar.id).getList();
And there is also option to get Reminders, Attendees, Instances.
It works with lists or cursor and there a sample app to see how it looks and works.
In fact, there is support for all Android content providers like: Contacts, SMS, Calls, ...
Full doc with all options: https://github.com/EverythingMe/easy-content-providers/wiki/Android-providers
Hope it helped :)
Use this code get the calendar events for one day.
public static void readCalendarEvent(Context context) throws ParseException {
ContentResolver contentResolver = context.getContentResolver();
Calendar calendar = Calendar.getInstance();
String dtstart = "dtstart";
String dtend = "dtend";
SimpleDateFormat displayFormatter = new SimpleDateFormat("MMMM dd, yyyy (EEEE)");
stime=displayFormatter.format(calendar.getTime());
SimpleDateFormat startFormatter = new SimpleDateFormat("MM/dd/yy");
String dateString = startFormatter.format(calendar.getTime());
long after = calendar.getTimeInMillis();
SimpleDateFormat formatterr = new SimpleDateFormat("hh:mm:ss MM/dd/yy");
Calendar endOfDay = Calendar.getInstance();
Date dateCCC = formatterr.parse("23:59:59 " + dateString);
endOfDay.setTime(dateCCC);
cursor = contentResolver.query(Uri.parse("content://com.android.calendar/events"), (new String[] { "calendar_id", "title", "description", "dtstart", "dtend","eventTimezone", "eventLocation" }), "(" + dtstart + ">" + after + " and " + dtend + "<" + endOfDay.getTimeInMillis() + ")", null, "dtstart ASC");
/*String[] COLS={"calendar_id", "title", "description", "dtstart", "dtend","eventTimezone", "eventLocation"};
cursor = contentResolver.query(
CalendarContract.Events.CONTENT_URI, COLS,null, null, null);*/
gCalendar = new ArrayList<GoogleCalendar>();
try {
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
GoogleCalendar googleCalendar = new GoogleCalendar();
gCalendar.add(googleCalendar);
int calendar_id = cursor.getInt(0);
googleCalendar.setCalendar_id(calendar_id);
String title = cursor.getString(1);
googleCalendar.setTitle(title);
String description = cursor.getString(2);
googleCalendar.setDescription(description);
String dtstart1 = cursor.getString(3);
dt=convertDate(dtstart1,"hh:mm:ss");
googleCalendar.setDtstart(dt);
String dtend1 = cursor.getString(4);
googleCalendar.setDtend(dtend1);
String eventTimeZone=cursor.getString(5);
googleCalendar.setEventTimeZone(eventTimeZone);
String eventlocation = cursor.getString(6);
googleCalendar.setEventlocation(eventlocation);
}
}
} catch (AssertionError ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}