Progrommatically created Calendar not saved - android

I'm trying to create calendar by using code from this topic
private static void createCalendar( Context mContext, Account account)
{
final ContentValues v = new ContentValues();
v.put(CalendarContract.Calendars.NAME,"TEST");
v.put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, "TEST");
v.put(CalendarContract.Calendars.ACCOUNT_NAME, account.name);
v.put(CalendarContract.Calendars.ACCOUNT_TYPE, account.type);
v.put(CalendarContract.Calendars.CALENDAR_COLOR, Color.GREEN);
v.put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_OWNER);
v.put(CalendarContract.Calendars.OWNER_ACCOUNT, account.name);
// v.put(CalendarContract.Calendars._ID, 123);
v.put(CalendarContract.Calendars.SYNC_EVENTS, 1);
v.put(CalendarContract.Calendars.VISIBLE, 1);
Uri creationUri = asSyncAdapter(CalendarContract.Calendars.CONTENT_URI, account.name, account.type);
Uri calendarData = mContext.getContentResolver().insert(creationUri, v);
long id = Long.parseLong(calendarData.getLastPathSegment());
}
private static Uri asSyncAdapter(Uri uri, String account, String accountType)
{
return uri.buildUpon().appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true").appendQueryParameter
(CalendarContract.Calendars.ACCOUNT_NAME,account)
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, accountType) .build();
}
and then make a call:
createCalendar(c, AccountManager.get(c).getAccountsByType("com.google")[0]); // i've checked - it's correct account to add calendar
Then i retrive data from ContentResolver
final ContentResolver cr = ctx.getContentResolver();
Cursor cursor ;
cursor = cr.query(Uri.parse("content://com.android.calendar/calendars"),null, null, null, null);
and see new calendar in cursor. But:
it not appears in google accound
it removes after some time (guess, because of synchronization)
tested on 5.1.1
How can I create calendar to my account progrommatically?

Try using calendar.insert to create another calendar.
Since you're using Java, I think this code snippet might be of help:
import com.google.api.services.calendar.Calendar;
// ...
// Initialize Calendar service with valid OAuth credentials
Calendar service = new Calendar.Builder(httpTransport, jsonFactory, credentials)
.setApplicationName("applicationName").build();
// Create a new calendar
com.google.api.services.calendar.model.Calendar calendar = new Calendar();
calendar.setSummary("calendarSummary");
calendar.setTimeZone("America/Los_Angeles");
// Insert the new calendar
Calendar createdCalendar = service.calendars().insert(calendar).execute();
System.out.println(createdCalendar.getId());
Give the Try-it a dry run to see if it works.

Related

How insert an event on Google Calendar

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.

Remove and Update existing Calendar Event

I am following this gist, to insert event into Calendar
How do I update existing Calendar Event, which i have inserted earlier using below code:
public void addToCalender() throws ParseException {
......
ContentValues event = new ContentValues();
event.put(CalendarContract.Events.CALENDAR_ID, calendarId[0]);
event.put(CalendarContract.Events.TITLE, "Event Title");
event.put(CalendarContract.Events.DESCRIPTION, "Event Description");
event.put(CalendarContract.Events.EVENT_LOCATION, "Eevnt Location");
event.put(CalendarContract.Events.DTSTART, startCalTime);
event.put(CalendarContract.Events.DTEND, endCalTime);
event.put(CalendarContract.Events.STATUS, 1);
event.put(CalendarContract.Events.HAS_ALARM, 1);
event.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());
Uri insertEventUri = AddEventActivity.this.getContentResolver().insert(
eventsUri, event);
ContentValues reminders = new ContentValues();
reminders.put(Reminders.EVENT_ID,
Long.parseLong(insertEventUri.getLastPathSegment()));
reminders.put(Reminders.METHOD, Reminders.METHOD_ALERT);
reminders.put(Reminders.MINUTES, 10);
AddEventActivity.this.getContentResolver().insert(remainderUri, reminders);
}
I would like to know, How do I :
1. Remove existing event
2. Update existing event
Here is how you can modify an event. Let's say its ID is eventID:
public void updateEvent(int eventID)
{
ContentResolver cr = context.getContentResolver();
Uri eventUri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventID);
ContentValues event = new ContentValues();
event.put(CalendarContract.Events.TITLE, "new title");
event.put(CalendarContract.Events.DESCRIPTION, "My cool event!");
cr.update(eventUri, event, null, null);
}
To remove an event, you have two possibilities:
If you are a standard application:
Use the previous code and replace all the event.put by this one:
event.put(CalendarContract.Events.DELETED, 1);
If you are the SyncAdapter of the calendar and want a real deletion (The previous method just says that the event should be deleted and the one that follows must be used once the calendar is being synced :
public deleteEvent(Uri eventUri)
{
cr.delete(event, null, null);
}
Where eventUri is the Uri of the event obtained as shown previously from the event ID.
For all of the previous methods, if you get an exception about not being in a sync adapter, you can use this:
public static Uri asSyncAdapter(Uri uri, String account, String accountType)
{
return uri.buildUpon()
.appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, account)
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, accountType)
.build();
}
I hope this will help you.
Source: personnal code + http://developer.android.com/guide/topics/providers/calendar-provider.html
...
Outlook in fact seems to respond to the rules defined in RFC 2446
In summary you have to specify
METHOD:REQUEST and ORGANIZER:xxxxxxxx
...
Please read the original answer by Tom Carter.

Calendar I created on "com.google" on android erased after sync

I created a new calendar on android and added events.
After first sync or after a few seconds it's erasing. Can somebody help with this problem?
Code:
private void createCalendar(Context context, String accName) {
Uri calUri = CalendarContract.Calendars.CONTENT_URI;
final ContentValues v = new ContentValues();
v.put(CalendarContract.Calendars.ACCOUNT_NAME, accName);
v.put(CalendarContract.Calendars.NAME, CALENDAR_NAME);
v.put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, CALENDAR_NAME);
v.put(CalendarContract.Calendars.ACCOUNT_TYPE, "com.google");
v.put(CalendarContract.Calendars.CALENDAR_COLOR, 0xEA8561);
v.put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_OWNER);
v.put(CalendarContract.Calendars.OWNER_ACCOUNT, accName);
v.put(CalendarContract.Calendars.SYNC_EVENTS, 1);
v.put(CalendarContract.Calendars.VISIBLE, 1);
calUri = calUri.buildUpon()
.appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, accName)
.appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, "com.google")
.build();
calUri = calUri.buildUpon().build();
final Uri result = context.getContentResolver().insert(calUri, v);
}
Unfortinately this is a known issue with the calendar API. you have only one option if you want to use the Android calendar- create the calendar as a local one and synchronize it yourself.

android - How to display local calendar?

I'm using the new Calendar API and I want to create a local calendar in my application on which the user can add custom events related to the app .. So I've been able to create it through this code:
/** Creates the values the new calendar will have */
private static ContentValues buildNewCalContentValues() {
final ContentValues cv = new ContentValues();
cv.put(Calendars.ACCOUNT_NAME, ACCOUNT_NAME);
cv.put(Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL);
cv.put(Calendars.NAME, CALENDAR_NAME);
cv.put(Calendars.CALENDAR_DISPLAY_NAME, CALENDAR_NAME);
cv.put(Calendars.CALENDAR_COLOR, 0xEA8561);
// user can only read the calendar
cv.put(Calendars.CALENDAR_ACCESS_LEVEL, Calendars.CAL_ACCESS_READ);
cv.put(Calendars.OWNER_ACCOUNT, ACCOUNT_NAME);
cv.put(Calendars.VISIBLE, 1);
cv.put(Calendars.SYNC_EVENTS, 1);
return cv;
}
//Create and insert new calendar into android database
public static void createCalendar(Context ctx) {
ContentResolver cr = ctx.getContentResolver();
final ContentValues cv = buildNewCalContentValues();
Uri calUri = buildCalUri();
// insert the calendar into the database
cr.insert(calUri, cv);
}
But the problem is I don't know how to display it and make the user interact with it.
Any help? Thanks in advance :)

write in the android calendar

As part of a project, I created an android application which communicates with an online database (MySQL) to integrate the appointment has taken the online calendar.
I collect the data, converted to Json, but when the inscrires in the agenda of android mobile I encounter a probleme, here is my code : (sorry for my english )
EDIT :
public class calendrier extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Cursor cursor = getContentResolver()
.query(Uri.parse("content://com.android.calendar/calendars"),
new String[] { "_id", "displayName" }, "selected=1",
null, null);
if (cursor != null && cursor.moveToFirst()) {
String[] calNames = new String[cursor.getCount()];
int[] calIds = new int[cursor.getCount()];
for (int i = 0; i < calNames.length; i++) {
calIds[i] = cursor.getInt(0);
calNames[i] = cursor.getString(1);
cursor.moveToNext();
}
cursor.close();
if (calIds.length > 0) {
// we're safe here to do any further work
}
// grab calendar id from above
int cal_id = calIds[0];
// set the content value
ContentValues cv = new ContentValues();
cv.put("calendar_id", cal_id);
cv.put("title", "titre");
cv.put("description", "bla bla bla");
cv.put("eventLocation", "city");
// note: you're going to need to convert the desired date into
// milliseconds
cv.put("dtstart", System.currentTimeMillis());
cv.put("dtend", System.currentTimeMillis()
+ DateUtils.DAY_IN_MILLIS);
cv.put("allDay", 0); // true = 1, false = 0
cv.put("hasAlarm", 1);
// once desired fields are set, insert it into the table
getContentResolver().insert(
Uri.parse("content://com.android.calendar/events"), cv);
}
}
}
this code works but it asks me if I want to participate in the event when I open it and I wish he does not do
thanks
//did U include permission in your manifest.xml file
android.permission.READ_CALENDAR
android.permission.WRITE_CALENDAR
String WRITE_CALENDAR Allows an application to write (but not read) the user's calendar data.
The Uri of Calendar has changed from Android 2.2 .
Old (2.1 and before): content://calendar/
New (2.2): content://com.android.calendar/
Change your Uri to the new one.
There is no Calendar Application by default in Android. So the Uri may not work at all.
If, you are getting the first error message as "Failed to find provider info for com.android.calendar", you need to check the handset you are using to debug uses which Calendar URI.
To insert Time in Calendar event, you can use the following code example:
Calendar calendar = Calendar.getInstance();
calendar.getTimeInMillis();
cv.put("dtstart", ""+calendar.getTimeInMillis());
cv.put("dtend", ""+calendar.getTimeInMillis()+10000);

Categories

Resources