Android Calendar, Invalid column display name - android

Hi i need to implement a code for insert, update events on android calendar, When i was trying add Events on Android Calendar it throws exception - invalid column displayname.
i try to replace deprecated , because apps crash:
Cursor l_managedCursor = this.managedQuery(l_eventUri, l_projection, "calendar_id=" + m_selectedCalendarId, null, "dtstart DESC, dtend DESC");
with this , but i received error by logcat "invalid column displayname"
Cursor l_managedCursor = getContentResolver().query (l_calendars, l_projection,null,null,null);
this is code
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/*get calendar list and populate the view*/
getCalendars();
populateCalendarSpinner();
populateAddBtn();
populateAddBtn2();
populateTextEvent();
populateGetEventsBtn();
}
private void populateCalendarSpinner() {
m_spinner_calender = (Spinner)this.findViewById(R.id.spinner_calendar);
ArrayAdapter l_arrayAdapter = new ArrayAdapter(this.getApplicationContext(), android.R.layout.simple_spinner_item, m_calendars);
l_arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
m_spinner_calender.setAdapter(l_arrayAdapter);
m_spinner_calender.setSelection(0);
m_spinner_calender.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> p_parent, View p_view,
int p_pos, long p_id) {
m_selectedCalendarId = m_calendars[(int)p_id].id;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {}
});
}
private void populateAddBtn() {
m_button_add = (Button) this.findViewById(R.id.button_add);
m_button_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addEvent();
}
});
}
private void populateAddBtn2() {
m_button_add2 = (Button) this.findViewById(R.id.button_add2);
m_button_add2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addEvent2();
}
});
}
private void populateGetEventsBtn() {
m_button_getEvents = (Button) findViewById(R.id.button_get_events);
m_button_getEvents.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getLastThreeEvents();
}
});
}
private void populateTextEvent() {
m_text_event = (TextView) findViewById(R.id.text_event);
String l_str = "title: roman10 calendar tutorial test\n" +
"description: This is a simple test for calendar api\n" +
"eventLocation: #home\n" +
"start time:" + getDateTimeStr(0) + "\n" +
"end time: " + getDateTimeStr(30) + "\n" +
"event status: confirmed\n" +
"all day: no\n" +
"has alarm: yes\n";
m_text_event.setText(l_str);
}
/****************************************************************
* Data part
*/
/*retrieve a list of available calendars*/
private MyCalendar m_calendars[];
private String m_selectedCalendarId = "0";
private void getCalendars() {
String[] l_projection = new String[]{"_id", "displayName"};
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");
}
// Cursor l_managedCursor = this.managedQuery(l_calendars, l_projection, null, null, null); //all calendars
//Cursor l_managedCursor = this.managedQuery(l_calendars, l_projection, "selected=1", null, null); //active calendars
Cursor l_managedCursor = getContentResolver().query (l_calendars, l_projection, "selected=1", null, null); //all calendars
if (l_managedCursor.moveToFirst()) {
m_calendars = new MyCalendar[l_managedCursor.getCount()];
String l_calName;
String l_calId;
int l_cnt = 0;
int l_nameCol = l_managedCursor.getColumnIndex(l_projection[1]);
int l_idCol = l_managedCursor.getColumnIndex(l_projection[0]);
do {
l_calName = l_managedCursor.getString(l_nameCol);
l_calId = l_managedCursor.getString(l_idCol);
m_calendars[l_cnt] = new MyCalendar(l_calName, l_calId);
++l_cnt;
} while (l_managedCursor.moveToNext());
}
}
/*add an event to calendar*/
private void addEvent() {
ContentValues l_event = new ContentValues();
l_event.put("calendar_id", m_selectedCalendarId);
l_event.put("title", "roman10 calendar tutorial test");
l_event.put("description", "This is a simple test for calendar api");
l_event.put("eventLocation", "#home");
l_event.put("dtstart", System.currentTimeMillis());
l_event.put("dtend", System.currentTimeMillis() + 1800*1000);
l_event.put("allDay", 0);
//status: 0~ tentative; 1~ confirmed; 2~ canceled
l_event.put("eventStatus", 1);
//0~ default; 1~ confidential; 2~ private; 3~ public
l_event.put("visibility", 0);
//0~ opaque, no timing conflict is allowed; 1~ transparency, allow overlap of scheduling
l_event.put("transparency", 0);
//0~ false; 1~ true
l_event.put("hasAlarm", 1);
Uri l_eventUri;
if (Build.VERSION.SDK_INT >= 8) {
l_eventUri = Uri.parse("content://com.android.calendar/events");
} else {
l_eventUri = Uri.parse("content://calendar/events");
}
Uri l_uri = this.getContentResolver().insert(l_eventUri, l_event);
Log.v("++++++test", l_uri.toString());
}
private void addEvent2() {
Intent l_intent = new Intent(Intent.ACTION_EDIT);
l_intent.setType("vnd.android.cursor.item/event");
//l_intent.putExtra("calendar_id", m_selectedCalendarId); //this doesn't work
l_intent.putExtra("title", "roman10 calendar tutorial test");
l_intent.putExtra("description", "This is a simple test for calendar api");
l_intent.putExtra("eventLocation", "#home");
l_intent.putExtra("beginTime", System.currentTimeMillis());
l_intent.putExtra("endTime", System.currentTimeMillis() + 1800*1000);
l_intent.putExtra("allDay", 0);
//status: 0~ tentative; 1~ confirmed; 2~ canceled
l_intent.putExtra("eventStatus", 1);
//0~ default; 1~ confidential; 2~ private; 3~ public
l_intent.putExtra("visibility", 0);
//0~ opaque, no timing conflict is allowed; 1~ transparency, allow overlap of scheduling
l_intent.putExtra("transparency", 0);
//0~ false; 1~ true
l_intent.putExtra("hasAlarm", 1);
try {
startActivity(l_intent);
} catch (Exception e) {
Toast.makeText(this.getApplicationContext(), "Sorry, no compatible calendar is found!", Toast.LENGTH_LONG).show();
}
}
private void getLastThreeEvents() {
Uri l_eventUri;
if (Build.VERSION.SDK_INT >= 8) {
l_eventUri = Uri.parse("content://com.android.calendar/events");
} else {
l_eventUri = Uri.parse("content://calendar/events");
}
String[] l_projection = new String[]{"title", "dtstart", "dtend"};
//Cursor l_managedCursor = this.managedQuery(l_eventUri, l_projection, "calendar_id=" + m_selectedCalendarId, null, "dtstart DESC, dtend DESC");
//Cursor l_managedCursor = this.managedQuery(l_eventUri, l_projection, null, null, null);
Cursor l_managedCursor = this.getContentResolver().query(l_eventUri, l_projection, "calendar_id=" + m_selectedCalendarId, null, "dtstart DESC, dtend DESC");
if (l_managedCursor.moveToFirst()) {
int l_cnt = 0;
String l_title;
String l_begin;
String l_end;
StringBuilder l_displayText = new StringBuilder();
int l_colTitle = l_managedCursor.getColumnIndex(l_projection[0]);
int l_colBegin = l_managedCursor.getColumnIndex(l_projection[1]);
int l_colEnd = l_managedCursor.getColumnIndex(l_projection[1]);
do {
l_title = l_managedCursor.getString(l_colTitle);
l_begin = getDateTimeStr(l_managedCursor.getString(l_colBegin));
l_end = getDateTimeStr(l_managedCursor.getString(l_colEnd));
l_displayText.append(l_title + "\n" + l_begin + "\n" + l_end + "\n----------------\n");
++l_cnt;
} while (l_managedCursor.moveToNext() && l_cnt < 3);
m_text_event.setText(l_displayText.toString());
}
}
/************************************************
* utility part
*/
private static final String DATE_TIME_FORMAT = "yyyy MMM dd, HH:mm:ss";
public static String getDateTimeStr(int p_delay_min) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_TIME_FORMAT);
if (p_delay_min == 0) {
return sdf.format(cal.getTime());
} else {
Date l_time = cal.getTime();
//l_time.getMinutes (l_time.getMinutes() + p_delay_min);
return sdf.format(l_time);
}
}
public static String getDateTimeStr(String p_time_in_millis) {
SimpleDateFormat sdf = new SimpleDateFormat(DATE_TIME_FORMAT);
Date l_time = new Date(Long.parseLong(p_time_in_millis));
return sdf.format(l_time);
}
}
LOGCAT
01-05 17:09:26.690 2354-2354/app.android.ny E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: app.android.ny, PID: 2354
java.lang.RuntimeException: Unable to start activity ComponentInfo{app.android.ny/app.android.ny.Main}: java.lang.IllegalArgumentException: Invalid column displayName
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.IllegalArgumentException: Invalid column displayName
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:167)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:137)
at android.content.ContentProviderProxy.query(ContentProviderNative.java:420)
at android.content.ContentResolver.query(ContentResolver.java:478)
at android.content.ContentResolver.query(ContentResolver.java:422)
at app.android.ny.Main.getCalendars(Main.java:136)
at app.android.ny.Main.onCreate(Main.java:58)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            
           

I Think there is a change in the way you query the calendars for newer API. They didn't seem to inform about it.
For API 10 I know displayName works.
For API >= 14 this code will work:
https://developer.android.com/guide/topics/providers/calendar-provider.html
// Projection array. Creating indices for this array instead of doing
// dynamic lookups improves performance.
public static final String[] EVENT_PROJECTION = new String[] {
Calendars._ID, // 0
Calendars.ACCOUNT_NAME, // 1
Calendars.CALENDAR_DISPLAY_NAME, // 2
Calendars.OWNER_ACCOUNT // 3
};
// Run query
Cursor cur = null;
ContentResolver cr = getContentResolver();
Uri uri = Calendars.CONTENT_URI;
String selection = "((" + Calendars.ACCOUNT_NAME + " = ?) AND ("
+ Calendars.ACCOUNT_TYPE + " = ?) AND ("
+ Calendars.OWNER_ACCOUNT + " = ?))";
String[] selectionArgs = new String[] {"sampleuser#gmail.com", "com.google",
"sampleuser#gmail.com"};
// Submit the query and get a Cursor object back.
cur = cr.query(uri, EVENT_PROJECTION, selection, selectionArgs, null);

Your app is crashing because the column name you are passing to get calender info is wrong. Change this line
String[] l_projection = new String[]{"_id", "displayName"};
in method getCalendars() to
String[] l_projection = new String[]{"_id", "calendar_displayName"};

You must have entered a different Column name. Kindly check the Upper case and lower case !!

Even I was facing this error, finaly got it done by this piece of code, hope this will help many
new String[] { "_id", Calendars.CALENDAR_DISPLAY_NAME }

Related

Is it possible to add a reminder programatically without creating event in android calendar?

I use Google Calendar Provider for Android to add Events in my Google Calendar:
https://developer.android.com/guide/topics/providers/calendar-provider.html#overview
And this is the example to add Reminder for the Event:
ContentValues values = new ContentValues();
values.put(CalendarContract.Reminders.MINUTES, 15);
values.put(CalendarContract.Reminders.EVENT_ID, reminderEventId);
values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);
getContentResolver().insert(CalendarContract.Reminders.CONTENT_URI, values);
But in my Google Calendar app I can create Reminders without having EVENT_ID. Is it possible to create the same reminders with Google Calendar Provider for Android?
The same like this:
https://gsuiteupdates.googleblog.com/2016/04/launch-of-reminders-for-google-calendar.html
I have see that Google launch reminders for Google Calendar 2016 (This is a different Reminders from Event Reminders) and at the moment I can`t find in Android SDK (API 25) this kind of Google Calendar Reminders (and possibility to add programmatically appointment slots too).
A tricky approach I'm using is creating the remainders, instead of calendar, in the contacts, using Custom Reminder (and the ContactContract provider). So, you can use any label, and the reminder is shown in the specific date.
Cons:
- You have to have the "Birthday" calendar enable
- The remainder is date based (not time)
- They don't repeat the reminder (as the new calendar does)
package es.goodsal.mobile.provider.contact;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.provider.ContactsContract.CommonDataKinds.Event;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import es.goodsal.mobile.app.App;
import es.goodsal.mobile.model.ReminderType;
/**
* Created by jmalbarran on 16/9/17.
*/
public class Reminder implements Comparable<Reminder> {
private static final String TAG = Reminder.class.getSimpleName();
private static final SimpleDateFormat fullPeriodicDateFormat = new SimpleDateFormat("--MM-dd");
private static final SimpleDateFormat periodicDateFormat = new SimpleDateFormat("MM-dd");
private static final SimpleDateFormat nonPeriodicDateFormat = new SimpleDateFormat("yyyy-MM-dd");
private static final String DUE_DATE = Event.DATA4;
private static final String COMMENT = Event.DATA5;
private static final Uri CONTENT_URI = ContactsContract.Data.CONTENT_URI;
private static final String[] PROJECTION = new String[]{
Event._ID, //0
Event.CONTACT_ID, //1
Event.LOOKUP_KEY, //2
Event.START_DATE, //3
Event.TYPE, //4
Event.LABEL, //5 Label for custom event
Reminder.DUE_DATE, // 6
Reminder.COMMENT // 7 Use this field to save Comments
};
static {
periodicDateFormat.setCalendar(Calendar.getInstance()); // Set local time zone
nonPeriodicDateFormat.setCalendar(Calendar.getInstance()); // Set local time zone
}
private long id = -1;
private ConContact contact;
private Date reminderDate;
private Date dueDate;
private ReminderType type;
private String comment;
// region Constructor
public Reminder(ConContact contact, Date reminderDate,
Date dueDate, ReminderType type, String comment) {
this.contact = contact;
this.reminderDate = reminderDate;
this.dueDate = dueDate;
this.type = type;
this.comment = comment;
}
public Reminder(#NonNull String reminderUri) {
this(Uri.parse(reminderUri));
}
public Reminder(#NonNull Uri reminderUri) {
Cursor cursor;
cursor = App.getContentResolverInstance().query(reminderUri,
PROJECTION, null, null, null);
if (cursor == null) {
throw new IllegalArgumentException(reminderUri.toString() + " opportunity not found.");
} else {
cursor.moveToFirst();
setFromCursor(null, cursor);
}
}
private Reminder(#NonNull Cursor cursor) {
this(null, cursor);
}
private Reminder(#Nullable ConContact contact, #NonNull Cursor cursor) {
setFromCursor(contact, cursor);
}
private void setFromCursor(#Nullable ConContact contact, #NonNull Cursor cursor) {
int eventType;
String eventLabel;
Calendar calDueDate, calReminderDate;
Date now;
String strSplitDate[];
String strDueDate;
this.id = cursor.getLong(0);
if (contact != null) {
this.contact = contact;
} else {
this.contact = new ConContact(cursor.getLong(1), cursor.getString(2));
}
// Type
eventType = cursor.getInt(4); //Event.TYPE
eventLabel = cursor.getString(5); //Event.LABEL
switch (eventType) {
case ContactsContract.CommonDataKinds.Event.TYPE_ANNIVERSARY:
type = ReminderType.anniversary;
break;
case ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY:
type = ReminderType.birthday;
break;
case ContactsContract.CommonDataKinds.Event.TYPE_CUSTOM:
type = ReminderType.other;
eventLabel = cursor.getString(5);
for (ReminderType iType : ReminderType.values()) {
if (iType.getLabel().equals(eventLabel)) {
type = iType;
break;
}
}
break;
default:
type = ReminderType.other;
}
// Due / Reminder date
try {
now = new Date();
if (type.isPeriodic()) {
// Periodic Due date
calDueDate = Calendar.getInstance();
calDueDate.setTime(now);
strSplitDate = cursor.getString(6).split("-"); // DATA4
if (strSplitDate != null && strSplitDate.length == 3) {
calDueDate.set(Calendar.MONTH, Integer.parseInt(strSplitDate[1]));
calDueDate.set(Calendar.DAY_OF_MONTH, Integer.parseInt(strSplitDate[2]));
if (calDueDate.before(now)) { // Crossed end-of-year boundary
calDueDate.add(Calendar.YEAR, 1); // Next year
}
} else {
Log.e(TAG, "getReminders: Invalid date for periodic reminder due date " +
cursor.getString(6));
}
dueDate = calDueDate.getTime();
// Periodic Reminder date
calReminderDate = Calendar.getInstance();
calReminderDate.setTime(dueDate);
strSplitDate = cursor.getString(3).split("-"); // START_DATE
if (strSplitDate != null && strSplitDate.length == 3) {
calReminderDate.set(Calendar.MONTH, Integer.parseInt(strSplitDate[1]));
calReminderDate.set(Calendar.DAY_OF_MONTH, Integer.parseInt(strSplitDate[2]));
if (calReminderDate.after(dueDate)) { // Crossed end-of-year boundary
calDueDate.add(Calendar.YEAR, -11); // Previous year
}
} else {
Log.e(TAG, "getReminders: Invalid date for periodic reminder start date " +
cursor.getString(6));
}
reminderDate = calReminderDate.getTime();
} else {
// Non periodic date
reminderDate = nonPeriodicDateFormat.parse(cursor.getString(3)); // START_DATE
dueDate = nonPeriodicDateFormat.parse(cursor.getString(6)); // DATA4
dueDate = dueDate !=null ? dueDate : reminderDate;
}
} catch (Exception e) { // NullPointer and/or ParseFormat
dueDate = null;
reminderDate = null;
}
// Comment
comment = cursor.getString(7); // DATA5
}
// endregion Constructor
// region Getter/Setter
public Uri getUri() {
Uri uri;
uri = null;
if (id != -1) {
uri = ContentUris.withAppendedId(CONTENT_URI, id);
}
return uri;
}
public ConContact getContact() {
return contact;
}
public Date getReminderDate() {
return reminderDate;
}
public Date getDueDate() {
return dueDate;
}
public ReminderType getReminderType() {
return type;
}
public String getComment() {
return comment;
}
public boolean isPeriodic() {
return type.isPeriodic();
}
public void setContact(ConContact contact) {
this.contact = contact;
}
public void setReminderDate(Date reminderDate) {
this.reminderDate = reminderDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
public void setType(ReminderType type) {
this.type = type;
}
public void setComment(String comment) {
this.comment = comment;
}
// endregion Getter/Setter
// region Commands
public boolean save() {
boolean ret;
ContentValues values;
Uri savedUri;
ret = false;
values = new ContentValues();
values.put(ContactsContract.CommonDataKinds.Event.MIMETYPE,
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE);
//values.put(ContactsContract.CommonDataKinds.Event.CONTACT_ID, contact.getContactId());
values.put(ContactsContract.CommonDataKinds.Event.RAW_CONTACT_ID, contact.getRawContactId());
if (type.isPeriodic()) {
values.put(ContactsContract.CommonDataKinds.Event.START_DATE,
fullPeriodicDateFormat.format(reminderDate));
values.put(ContactsContract.CommonDataKinds.Event.DATA4,
fullPeriodicDateFormat.format(dueDate));
} else {
values.put(ContactsContract.CommonDataKinds.Event.START_DATE,
nonPeriodicDateFormat.format(reminderDate));
values.put(ContactsContract.CommonDataKinds.Event.DATA4,
nonPeriodicDateFormat.format(dueDate));
}
values.put(ContactsContract.CommonDataKinds.Event.TYPE,
Integer.toString(type.getContactEventType()));
values.put(ContactsContract.CommonDataKinds.Event.LABEL, type.getLabel());
values.put(ContactsContract.CommonDataKinds.Event.DATA5, comment);
if (id == -1L) {
// Create new
savedUri = App.getContentResolverInstance().insert(ContactsContract.Data.CONTENT_URI, values);
id = ContentUris.parseId(savedUri);
ret = true;
Log.d(TAG, "save: Inserted uri=" + savedUri + " id=" + id);
} else {
// update existing id
// if (0<App.getContentResolverInstance().update(ContactsContract.Data.CONTENT_URI, values,
// ContactsContract.Data._ID + "='" + Long.toString(id) + "'", null)){
if (0 < App.getContentResolverInstance().update(
ContentUris.withAppendedId(ContactsContract.Data.CONTENT_URI, id),
values,
null,
null)) {
ret = true;
Log.d(TAG, "save: Updated id=" + id);
} else {
Log.e(TAG, "save: Error updating id=" + id);
}
}
contact.resetReminders();
return ret;
}
public boolean delete() {
boolean ret = false;
if (id != -1) {
if (0 < App.getContentResolverInstance().delete(
ContentUris.withAppendedId(ContactsContract.Data.CONTENT_URI, id),
null,
null)) {
Log.d(TAG, "delete: Deleted id=" + id);
ret = true;
} else {
Log.w(TAG, "delete: Not found id=" + id);
}
}
return ret;
}
// endregion Commands
#Override
public int compareTo(#NonNull Reminder o) {
if (reminderDate == null) {
return 1; // null always at end
} else {
if (o.reminderDate == null) {
return -1;
} else {
return reminderDate.compareTo(o.reminderDate);
}
}
}
/**
* Get reminders for all contact, in a specific date (including periodics)
*
* #param date exact to search for (reminder date NOT due date)
* #return List of reminders
*/
public static List<Reminder> getReminders(Date date) {
Cursor cursor;
ArrayList<Reminder> retList;
String where;
String[] selectionArgs;
Date dueDate;
String dateSelection;
String[] strSplitDate;
Calendar calDueDate;
retList = null;
Uri uri = ContactsContract.Data.CONTENT_URI;
String sortOrder = null;
// Execute one query per reminder type
for (ReminderType type : ReminderType.values()) {
dateSelection = type.isPeriodic() ?
"%" + periodicDateFormat.format(date) :
"%" + nonPeriodicDateFormat.format(date);
if (type.getContactEventType() == ContactsContract.CommonDataKinds.Event.TYPE_CUSTOM) {
// Check event label too
where = ContactsContract.CommonDataKinds.Event.MIMETYPE + "= ? AND " +
ContactsContract.CommonDataKinds.Event.START_DATE + " LIKE ? AND " +
ContactsContract.CommonDataKinds.Event.LABEL + "= ? AND " +
ContactsContract.CommonDataKinds.Event.TYPE + "=" + type.getContactEventType();
selectionArgs = new String[]{
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE,
dateSelection,
type.getLabel()
};
} else {
// Non custom reminder. Don't check label
where = ContactsContract.CommonDataKinds.Event.MIMETYPE + "= ? AND " +
ContactsContract.CommonDataKinds.Event.START_DATE + " LIKE ? AND " +
ContactsContract.CommonDataKinds.Event.TYPE + "=" + type.getContactEventType();
selectionArgs = new String[]{
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE,
dateSelection
};
} // where & selection per event type
cursor = App.getContentResolverInstance().query(uri, PROJECTION,
where, selectionArgs, sortOrder);
if (cursor != null) {
retList = new ArrayList<Reminder>();
while (cursor.moveToNext()) {
retList.add(new Reminder(cursor));
}
cursor.close();
} // if cursor
} // for per every type
return retList;
}
/**
* Get reminders for a specific contact, from a date forward
*
* #param contact Contact for search for
* #param date current or future date to search (including periodic)
* #return List of reminders for current or future search
*/
public static List<Reminder> getReminders(ConContact contact, Date date) {
Uri uri;
Cursor cursor;
ArrayList<Reminder> retList = null;
String where;
String[] selectionArgs;
String sortOrder;
int contactEventType;
String label;
Calendar calReminderDate, calDueDate;
String strReminderDate, strDueDate;
ReminderType type;
Date reminderDate;
Date dueDate;
String strDescription;
String[] strSplitDate;
uri = ContactsContract.Data.CONTENT_URI;
sortOrder = null;
// Check event label too
where = ContactsContract.CommonDataKinds.Event.MIMETYPE + " = ? AND " +
ContactsContract.CommonDataKinds.Event.CONTACT_ID + " = ? AND " +
"(" +
ContactsContract.CommonDataKinds.Event.START_DATE + " LIKE '--%' OR " +
ContactsContract.CommonDataKinds.Event.START_DATE + " >= ?" +
")";
selectionArgs = new String[]{
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE,
Long.toString(contact.getContactId()),
nonPeriodicDateFormat.format(date)
};
sortOrder = ContactsContract.CommonDataKinds.Event.START_DATE;
cursor = App.getContentResolverInstance().query(uri, PROJECTION,
where, selectionArgs, sortOrder);
if (cursor != null) {
retList = new ArrayList<Reminder>();
while (cursor.moveToNext()) {
retList.add(new Reminder(contact, cursor));
}
Collections.sort(retList);
cursor.close();
} // if cursor
// for per every type
return retList;
}
} // end Reminder class
As stated in https://developer.android.com/guide/topics/providers/calendar-provider.html#overview
Reminders are specified in minutes before the event and have a method
that determines how the user will be alerted.
A reminder that doesn't belong to an event will not have a time of reference to go off.
I think for what you are trying to achieve () it would be best for you to look at Androids AlarmManager https://developer.android.com/reference/android/app/AlarmManager.html
Or see what other people are saying about similar things https://stackoverflow.com/a/16549111/6431430

Calendar event color doesn't sync between my android app and google web calendar

After my android app sync event to google calendar and i see color google android calendar but doesn't change google web calendar event color. What i to do wrong?
Name is accountName.
protected void fetchCalendarForUser(String name) {
Cursor cur = null;
ContentResolver cr = getContentResolver();
Uri uri = CalendarContract.Calendars.CONTENT_URI;
String selection = "((" + CalendarContract.Calendars.ACCOUNT_NAME + " = ?) AND ("
+ CalendarContract.Calendars.ACCOUNT_TYPE + " = ?) AND ("
+ CalendarContract.Calendars.OWNER_ACCOUNT + " = ?))";
String[] selectionArgs = new String[] {name, "com.google", name};
cur = cr.query(uri, EVENT_PROJECTION, selection, selectionArgs, null);
cur.moveToNext();
long calID = 0;
String displayName = null;
String accountName = null;
String ownerName = null;
// Get the field values
calID = cur.getLong(PROJECTION_ID_INDEX);
displayName = cur.getString(PROJECTION_DISPLAY_NAME_INDEX);
accountName = cur.getString(PROJECTION_ACCOUNT_NAME_INDEX);
ownerName = cur.getString(PROJECTION_OWNER_ACCOUNT_INDEX);
int i = 0;
List<Date> laststart = new ArrayList<Date>();
List<Date> lastend = new ArrayList<Date>();
boolean equal=false;
for (Map.Entry<String, ArrayList<CalendarEntry>> item : calendarEntriesByDay.entrySet()) {
for (CalendarEntry entry : item.getValue()) {
for(int j=0;j<laststart.size();j++)
{
if(laststart.get(j) == entry.getStart()){
if(lastend.get(j) == entry.getEnd()){
equal=true;
}
}
}
if(equal==false) {
createEventOnCalendar(calID, entry);
i++;
}
else
{
equal=false;
}
laststart.add(entry.getStart());
lastend.add(entry.getEnd());
}
}
if (i > 0) {
Crouton.makeText(this, getResources().getString(eu.rerisoft.servicebus.R.string.google_calendar_add_success, displayName, String.valueOf(i)), Style.ALERT).show();
} else {
Crouton.makeText(this, eu.rerisoft.servicebus.R.string.google_calendar_add_error, Style.ALERT).show();
}
}
protected long createEventOnCalendar(long calID, CalendarEntry event) {
String colorString = getResources().getString(event.getColorRes());
int eventColor = Color.parseColor(colorString);
ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues();
values.put(CalendarContract.Events.DTSTART, event.getStart().getTime());
values.put(CalendarContract.Events.DTEND, event.getEnd().getTime());
values.put(CalendarContract.Events.TITLE, event.getTitle());
values.put(CalendarContract.Events.EVENT_COLOR, eventColor);
values.put(CalendarContract.Events.DESCRIPTION, event.getDescription());
values.put(CalendarContract.Events.CALENDAR_ID, calID);
values.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getTimeZone("UTC").getDisplayName());
Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
long eventID = Long.parseLong(uri.getLastPathSegment());
return eventID;
}
Sorry for bad english.
I have done same thing before 3 months:
String appointmentColorCode = "Color_which_Is_Currently_Getting_From_Calendar";
int mColorCode = 0;
mColorCode = (0xff000000 + Integer.parseInt(appointmentColorCode));
You have to give Color_which_Is_Currently_Getting_From_Calendar as you are getting from calendar.
mColorCode will be your final Color code.'
Done

Getting attendees details from Calendar Content Provider

I am trying to create a app which will fetch details of Events and Attendeesfrom Calendar app.
I am facing the problems which are"
1). In many of the events Title and their attendees does not match.
2). In many of the events I am getting 0 attendees
(mainly for upcoming events).
Here is my code: (Please let me know the mistake).
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[] { Calendars._ID, Calendars.NAME}), 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);
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);
Log.e("123", "Calender ID---->>>>>>"+id);
Cursor eventCursor = contentResolver.query(builder.build(),
new String[] { Events.TITLE, "begin", "end", "allDay", Events._ID, Events.CALENDAR_ID}, Events.CALENDAR_ID+"=" + id,
null, "_id ASC");
Log.e("123","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");
final String eventId = eventCursor.getString(4);
final String calendarID = eventCursor.getString(5);
Log.e("123", "Event Id----->>>>>"+eventId+"---------calendarId----->>>"+calendarID);
/* System.out.println("Title: " + title + " Begin: " + begin + " End: " + end +
" All Day: " + allDay);
*/
Log.e("123","Title:"+title);
Log.e("123","Begin:"+begin);
Log.e("123","End:"+end);
Log.e("123","All Day:"+allDay);
// Attendees Code
Cursor eventAttendeesCoursor = contentResolver.query(CalendarContract.Attendees.CONTENT_URI, new String []{ Attendees.ATTENDEE_NAME, Attendees.EVENT_ID}, Attendees.EVENT_ID +" = " + eventId, null, null);
Log.e("123", "Count of no of attendees-----"+eventAttendeesCoursor.getCount());
if(eventAttendeesCoursor.getCount()>0)
{
if(eventAttendeesCoursor.moveToFirst())
{
do {
// Log.e("123", "Attendees Name---->>>"+ eventAttendeesCoursor.getString(0));
Log.e("123", "Attendees Event ID---->>>"+ eventAttendeesCoursor.getString(1));
} while(eventAttendeesCoursor.moveToNext());
}
}
}
while(eventCursor.moveToNext());
}
}
break;
}
}
}

Adding events to android calendar failing

I am trying to add events to a user's calendar programatically. I have followed countless guides here on StackOverflow and elsewhere, but none of them will make that damned event show up in my calendar. Here is my current code:
public void saveGamesToCalendar() {
showCalendarPopup();
}
private void showCalendarPopup() {
final ContentResolver cr;
final Cursor result;
final Uri uri;
List<String> listCals = new ArrayList<String>();
final String[] projection = new String[] {CalendarContract.Calendars._ID, CalendarContract.Calendars.ACCOUNT_NAME, CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, CalendarContract.Calendars.NAME,};
uri = CalendarContract.Calendars.CONTENT_URI;
cr = context.getContentResolver();
result = cr.query(uri, projection, null, null, null);
if(result.getCount() > 0 && result.moveToFirst()) {
do {
listCals.add(result.getString(result.getColumnIndex(CalendarContract.Calendars.NAME)));
} while(result.moveToNext());
}
CharSequence[] calendars = listCals.toArray(new CharSequence[listCals.size()]);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Calendar to use:");
builder.setItems(calendars, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,int itemCal) {
Log.e("SettingsActivity", "CalendarID: " + itemCal);
loopThroughGames(itemCal);
};
});
AlertDialog alert = builder.create();
alert.show();
}
private void loopThroughGames(int whichCalendar) {
ArrayList<Model_Game> games = memoryManager.getGames();
// for(Game e: games)
Log.e("Game", games.get(101).toString());
addGameToCalendar(games.get(101), whichCalendar);
Log.e("ID", "" + whichCalendar);
}
private void addGameToCalendar(Model_Game game,int whichCalendar) {
ContentResolver cr = context.getContentResolver();
ContentValues values = new ContentValues();
try {
values.put(CalendarContract.Events.CALENDAR_ID, whichCalendar);
values.put(CalendarContract.Events.TITLE, "Hockey- " + game.getLeague() + ": " + game.getTeamH() + " vs " + game.getTeamA());
values.put(CalendarContract.Events.EVENT_LOCATION, "Twin Rinks Ice Arena- " + game.getRink() + " Rink");
values.put(CalendarContract.Events.DTSTART, "" + game.getCalendarObject().getTimeInMillis());
//values.put(CalendarContract.Events.DTEND, "" + game.getCalendarObject().getTimeInMillis() + 5400000);
values.put(CalendarContract.Events.DURATION, "" + 5400000);
values.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
cr.insert(CalendarContract.Events.CONTENT_URI, values);
} catch(Exception e) {
Log.e("Error", e.getMessage());
toast(e.getMessage());
}
}
Basically what is going on is that the user presses an action bar button, which calls the saveGamesToCalendar() method, which calls the ShowCalendarPopup() method. This method shows a standard dialog with the list of the user's calendars, and when the user selects one of them, the loopThroughGames() method is called with the ID of the chosen calendar as a parameter. This method will, when everything is working, write all the user's games to the calendar, but for testing purposes it only writes one. The addGameToCalendar() method takes a game object, which holds lots of values like time, title, location, date, etc., and inserts it into the calendar using the standard way outlined in many different places on the web.
I am getting no error messages with this code (other than the ones I send to the error log myself) so I have no idea why this code isn't working. No errors, just the games never show up in my calendar. I have the permissions set correctly in the manifest so I know that isn't the problem.
Does anyone have a solution to this annoying problem? Thanks for your help!
[RE-EDIT]]
This is what I did and it works like a charm..
Cursor cursor = null ;
String[] projection = new String[] {
CalendarContract.Calendars._ID,
CalendarContract.Calendars.ACCOUNT_NAME,};
ContentResolver cr = context2.getContentResolver();
cursor = cr.query(Uri.parse("content://com.android.calendar/calendars"), projection, null, null, null);
if ( cursor.moveToFirst() ) {
final String[] calNames = new String[cursor.getCount()];
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();
}
}
try {
ContentValues values = new ContentValues();
// int apiLevel = android.os.Build.VERSION.SDK_INT;
// if(apiLevel<14){
// values.put("visibility", 0);
//
// }
values.put(Events.DTSTART, stTime);
values.put(Events.DTEND, enTime);
values.put(Events.TITLE, category);
values.put(Events.DESCRIPTION, description);
values.put(Events.CALENDAR_ID, calIds[0]);
values.put(Events.EVENT_LOCATION,place);
values.put(Events.EVENT_TIMEZONE,tZone);
mInsert = cr.insert(CalendarContract.Events.CONTENT_URI, values);
Toast.makeText(context2, "Event added Successfully",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context2, "Exception: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
protected void eventAdding() {
try
{
Calendar beginTime = Calendar.getInstance();
beginTime.set(2013, 11, 20, 8,0 );
startMillis = beginTime.getTimeInMillis();
Calendar endTime = Calendar.getInstance();
endTime.set(2013, 11, 20, 8, 50);
endMillis = endTime.getTimeInMillis();
ContentResolver cr = this.getContentResolver();
ContentValues values = new ContentValues();
values.put(Events.DTSTART, startMillis);
values.put(Events.DTEND, endMillis);
values.put(Events.TITLE, "Hello");
values.put(Events.CALENDAR_ID, 1);
values.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
if (android.os.Build.VERSION.SDK_INT <= 7) {
uri = Uri.parse("content://calendar/events");
} else
{
uri = Uri.parse("content://com.android.calendar/events");
}
Uri urievent = cr.insert(uri, values);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//event = Utility.readCalendarEvent(CalnderEvent.this);
}
This works and is much easier to understand:
long startTime = calSet.getTimeInMillis();
Intent intent = new Intent(Intent.ACTION_INSERT).setData(Events.CONTENT_URI)
.setData(Events.CONTENT_URI)
.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startTime)
.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, startTime + (length*3600000))
.putExtra(Events.TITLE, examName)
.putExtra(Events.EVENT_LOCATION, venue)
.putExtra(Events.AVAILABILITY, Events.AVAILABILITY_BUSY)
.putExtra(Events.HAS_ALARM, 1);
startActivity(intent);

Android Calendar Events

I am just making an operation with Calendar Content Provider, now I am failing at the point to display events for the particular date.
I know the Events URI for the < 2.1 version and 2.2 version, as below:
eventsUri = Uri.parse("content://calendar/events"); // < Android 2.1 version
eventsUri = Uri.parse("content://com.android.calendar/events"); // For Android Froyo 2.2 and later version
My doubts are:
How do I Fetch all the events?
How do I fetch events for the particular date?
So please, somebody with knowledge about the Calendar please help me and share your knowledge regarding this.
Thanx
These examples are for <= 2.1 version;
first; find out which calendars exist
Cursor cursor = cr.query(Uri.parse("content://calendar/calendars"), new String[]{ "_id", "displayname" }, null, null, 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();
Fetching all events, and particular event is done by specifying range
ContentResolver contentResolver = getContentResolver();
Uri.Builder builder = Uri.parse(getCalendarUriBase() + "/instances/when").buildUpon();
long now = new Date().getTime();
ContentUris.appendId(builder, now - DateUtils.MILLIS_PER_DAY*10000);
ContentUris.appendId(builder, now + DateUtils.MILLIS_PER_DAY * 10000);
and then let's say you wish to log events ID from calendar with ID = 1
Cursor eventCursor = contentResolver.query(builder.build(),
new String[] { "event_id"}, "Calendars._id=" + 1,
null, "startDay ASC, startMinute ASC");
// For a full list of available columns see http://tinyurl.com/yfbg76w
while (eventCursor.moveToNext()) {
String uid2 = eventCursor.getString(0);
Log.v("eventID : ", uid2);
}
// Here's a way for you to get all the Calendar events list
public static void readCalendarEvent(Context context) {
ContentResolver contentResolver = context.getContentResolver();
cursor = contentResolver.query(Uri.parse("content://com.android.calendar/events"), (new String[] { "_id", "title", "organizer", "dtstart", "dtend"}), null, null, null);
List<GoogleCalendar> gCalendar = new ArrayList<GoogleCalendar>();
try {
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
GoogleCalendar googleCalendar = new GoogleCalendar();
int event_ID = cursor.getInt(0);
googleCalendar.setEvent_id(event_ID);
String title = cursor.getString(1);
googleCalendar.setTitle(title);
String mOrganizer = cursor.getString(2);
googleCalendar.setOrganizer(mOrganizer);
String dtStart = cursor.getString(3);
googleCalendar.setDtstart(dtStart);
String dtEnd = cursor.getString(4);
googleCalendar.setDtend(dtEnd);
gCalendar.add(googleCalendar);
Log.d("CaledarM",googleCalendar.getTitle()+" name = "+googleCalendar.getOrganizer()+" dateStart = "+googleCalendar.getDtstart()+" Size = " + gCalendar.size());
}
}
} catch (AssertionError ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// class GoogleCalendar()
public class GoogleCalendar {
private int event_id;
private String title,
organizer,
dtstart,
dtend;
public GoogleCalendar()
{
}
public int getEvent_id() {
return event_id;
}
public void setEvent_id(int calendar_id) {
event_id = calendar_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getOrganizer() {
return organizer;
}
public void setOrganizer(String description) {
this.organizer = description;
}
public String getDtstart() {
return dtstart;
}
public void setDtstart(String dtstart1) {
this.dtstart = dtstart1;
}
public String getDtend() {
return dtend;
}
public void setDtend(String dtend1) {
this.dtend = dtend1;
}
}
Use this code to get daily events,
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();
}
}
}

Categories

Resources