Default calendar id for android - android

I am trying to add event automatically but I need calendar id for this
If I add event to calendar with id = 1 sometimes it does not exist or does not depend to event I add
ContentValues cv = new ContentValues();
cv.put("calendar_id", 1);
id = -1 does not work
how can I add event to default calendar. what id should I use?

public MyCalendar [] getCalendar(Context c) {
String projection[] = {"_id", "calendar_displayName"};
Uri calendars;
calendars = Uri.parse("content://com.android.calendar/calendars");
ContentResolver contentResolver = c.getContentResolver();
Cursor managedCursor = contentResolver.query(calendars, projection, null, null, null);
if (managedCursor.moveToFirst()){
m_calendars = new MyCalendar[managedCursor.getCount()];
String calName;
String calID;
int cont= 0;
int nameCol = managedCursor.getColumnIndex(projection[1]);
int idCol = managedCursor.getColumnIndex(projection[0]);
do {
calName = managedCursor.getString(nameCol);
calID = managedCursor.getString(idCol);
m_calendars[cont] = new MyCalendar(calName, calID);
cont++;
} while(managedCursor.moveToNext());
managedCursor.close();
}
return m_calendars;}
You can try use this code for get a calendar id.
But check all guide - how add event to calendar.
https://stackoverflow.com/a/9749833/7046743

int calenderId=-1;
String calenderEmaillAddress="xxx#gmail.com";
String[] projection = new String[]{
CalendarContract.Calendars._ID,
CalendarContract.Calendars.ACCOUNT_NAME};
ContentResolver cr = activity.getContentResolver();
Cursor cursor = cr.query(Uri.parse("content://com.android.calendar/calendars"), projection,
CalendarContract.Calendars.ACCOUNT_NAME + "=? and (" +
CalendarContract.Calendars.NAME + "=? or " +
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME + "=?)",
new String[]{calenderEmaillAddress, calenderEmaillAddress,
calenderEmaillAddress}, null);
if (cursor.moveToFirst()) {
if (cursor.getString(1).equals(calenderEmaillAddress))
calenderId=cursor.getInt(0); //youre calender id to be insered in above your code
}

Related

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

not getting missed call value from call logs android

hey I am unable to get the call type == missed call and of current date only.
Its can be achieved from Cursor query i have tried this but getting Calls type as missed call
I am using this in onCreate method but not getting any value in logcat????
Here is my piece of code any help would be greatly appreciated......thanks in advance
String where = CallLog.Calls.TYPE+"="+CallLog.Calls.MISSED_TYPE;
int missedtype=CallLog.Calls.MISSED_TYPE;
String missed=Integer.toString(missedtype);
String timestamp = String.valueOf(getTodayTimestamp());
Cursor cursor = this.getContentResolver()
.query(CallLog.Calls.CONTENT_URI,
new String[] { CallLog.Calls.DATE, CallLog.Calls.TYPE,
CallLog.Calls.DURATION, CallLog.Calls.NUMBER,
CallLog.Calls._ID },
CallLog.Calls.DATE + ">?" + " and "
+ CallLog.Calls.TYPE + "=?",
new String[] { timestamp, String.valueOf(CallLog.Calls.MISSED_TYPE) },
CallLog.Calls.DATE);
//Cursor managedCursor = this.getContentResolver().query(CallLog.Calls.CONTENT_URI, null, CallLog.Calls.DATE + ">= ?", new String[]{timestamp}, null);
//Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI, null, where , null, CallLog.Calls.DATE+ " >= ?");
int number = cursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = cursor.getColumnIndex(CallLog.Calls.TYPE);
int date = cursor.getColumnIndex(CallLog.Calls.DATE);
int duration = cursor.getColumnIndex(CallLog.Calls.DURATION);
{
while (cursor.moveToNext()) {
String LogphNumber = cursor.getString(number);
String callType = cursor.getString(type);
String callDate = cursor.getString(date);
Date callDayTime = new Date(Long.valueOf(callDate));
String callDuration = cursor.getString(duration);
{
if(cursor.getCount()>1){
System.out.println("Total Logs::>>>>>>>>> "+cursor.getCount());
System.out.println("\nPhoneNo:----"+LogphNumber);
System.out.println("\nCallDate: "+callDayTime);
System.out.println("\nCallDuration in Seconds :"+callDuration);
System.out.println("\n-----------------------");
}else if(cursor.getCount()==0){
System.out.println("No Missed calls");
}
}
}cursor.close();
}
try this:
String timestamp = String.valueOf(getTodayTimestamp());
Cursor cursor = this.getContentResolver()
.query(CallLog.Calls.CONTENT_URI,
new String[] { CallLog.Calls.DATE, CallLog.Calls.TYPE,
CallLog.Calls.DURATION, CallLog.Calls.NUMBER,
CallLog.Calls._ID },
CallLog.Calls.DATE + ">?" + " and "
+ CallLog.Calls.TYPE + "=?",
new String[] { timestamp, String.valueOf(CallLog.Calls.MISSED_TYPE) },
CallLog.Calls.DATE);

Not able to fetch the correct Birthday and Anniversary data from Contact

I am able to fetch other information (Display name,organisation,phone no and email_id) of a contact, but not able to fetch birthday and anniversary of that contact.
Here is the code i am using for birthday. It does fetch the data, but gives me wrong data, i.e repeats the same data for all the contacts.
private String getBDate(String id) {
String bday = null;
ContentResolver cr = getContentResolver();
Uri uri = ContactsContract.Data.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Event.CONTACT_ID,
ContactsContract.CommonDataKinds.Event.START_DATE };
String where = ContactsContract.Data.MIMETYPE + "= ? AND "
+ ContactsContract.CommonDataKinds.Event.TYPE + "="
+ ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
String[] selectionArgs = new String[] { ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE };
String sortOrder = null;
Cursor cur = cr.query(uri, projection, where, selectionArgs, sortOrder);
while (cur.moveToNext()) {
bday = cur
.getString(cur
.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
Log.v("Birthday", bday);
}
cur.close();
return bday;
}
Same is the case with anniversary, here is the code for it. In some case anniversary is not added but it still shows the data from other contact.
private String getAnnv(String id) {
String annv = null;
ContentResolver cr = getContentResolver();
Uri uri = ContactsContract.Data.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Event.CONTACT_ID,
ContactsContract.CommonDataKinds.Event.START_DATE };
String where = ContactsContract.Data.MIMETYPE + "= ? AND "
+ ContactsContract.CommonDataKinds.Event.TYPE + "="
+ ContactsContract.CommonDataKinds.Event.TYPE_ANNIVERSARY;
String[] selectionArgs = new String[] { ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE };
// String sortOrder = null;
Cursor cur = cr.query(uri, projection, where, selectionArgs, null);
while (cur.moveToNext()) {
annv = cur
.getString(cur
.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
Log.v("Anniversary", annv);
}
cur.close();
return annv;
}
you are not using String id perameter in where condition so please check again.
E,g private String getAnnv(String id) function has input for ID but that seems to be not used withing function so please put that ID in condition check and this should work.
e.g
ContactsContract.CommonDataKinds.Event.CONTACT_ID + "= " + ID
AND ContactsContract.Data.MIMETYPE + "= ? AND "

I cant update the notes section of a contact

I'm trying to change the notes section of a contact, I got their phone number (receivedLocationSender) and the Log output gives the correct Name and ID, but idk how to get it to replace the "NOTES" section of the contact.. what I currently have does absolutely nothing.
private void displayContacts() {
ContentResolver contentResolver = getBaseContext().getContentResolver();
ContentValues contentValues = new ContentValues();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(receivedLocationSender));
String[] projection = new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup._ID};
Cursor cursor = contentResolver.query(
uri,
projection,
null,
null,
null);
if(cursor!=null) {
while(cursor.moveToNext()){
String contactName = cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
String contactId = cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup._ID));
contentValues.clear();
String noteWhereParams = ContactsContract.CommonDataKinds.Note.NOTE;
String[] args = new String[] { String.valueOf(receivedLocation) };
contentValues.put(ContactsContract.CommonDataKinds.Note.NOTE, receivedLocation);
getContentResolver().update(ContactsContract.Data.CONTENT_URI, contentValues, contactId + "=?", args);
Log.d(LOGTAG, "contactMatch name: " + contactName);
Log.d(LOGTAG, "contactMatch id: " + contactId);
Log.d(LOGTAG, "contactNotes : " + ContactsContract.CommonDataKinds.Note.NOTE.toString());
}
cursor.close();
}
}
After you have a contact id (id) from phonelookup.. the stuff below works
ContentResolver cr = this.getContentResolver();
ContentValues values = new ContentValues();
values.clear();
String noteWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] noteWhereParams = new String[]{id,ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
values.put(CommonDataKinds.Note.NOTE, "NEW NOTE HERE!!!!");
cr.update(ContactsContract.Data.CONTENT_URI, values, noteWhere, noteWhereParams);
Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, null, noteWhere, noteWhereParams, null);
if (noteCur.moveToFirst()) {
String note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
Log.d(LOGTAG, "notes : " + note);
}
noteCur.close();

Get Calendar Event by Date in Android?

I want to list of events from my calendar based on specific date. I am using following
Cursor cursor = getContentResolver().query(Uri.parse("content://com.android.calendar/events"), new String[]{ "_id", "title", "description", "dtstart", "dtend", "eventLocation" }, null, null, null);
This code works fine but it brings the total events from the calendar. But i need a events on specfic date like 2011-08-15. I tried following code
Cursor cursor = getContentResolver().query(Uri.parse("content://com.android.calendar/events"), new String[]{ "_id", "title", "description", "dtstart", "dtend", "eventLocation" }, "dtstart", new String[]{sdf.format(calender.getTime())}, null);
cursor.moveToFirst();
But I am getting exception
Caused by: android.database.sqlite.SQLiteException: no such column:
Calendars.dtstart: , while compiling: SELECT _id, title, description,
dtstart, dtend, eventLocation FROM view_events WHERE (1) AND
(Calendars.dtstart)
Please give some advise to solve my problem
I have done this way:
String[] projection = new String[] { CalendarContract.Events.CALENDAR_ID, CalendarContract.Events.TITLE, CalendarContract.Events.DESCRIPTION, CalendarContract.Events.DTSTART, CalendarContract.Events.DTEND, CalendarContract.Events.ALL_DAY, CalendarContract.Events.EVENT_LOCATION };
Calendar startTime = Calendar.getInstance();
startTime.set(Calendar.HOUR_OF_DAY,0);
startTime.set(Calendar.MINUTE,0);
startTime.set(Calendar.SECOND, 0);
Calendar endTime= Calendar.getInstance();
endTime.add(Calendar.DATE, 1);
String selection = "(( " + CalendarContract.Events.DTSTART + " >= " + startTime.getTimeInMillis() + " ) AND ( " + CalendarContract.Events.DTSTART + " <= " + endTime.getTimeInMillis() + " ) AND ( deleted != 1 ))";
Cursor cursor = context.getContentResolver().query(CalendarContract.Events.CONTENT_URI, projection, selection, null, null);
List<String> events = new ArrayList<>();
if (cursor!=null&&cursor.getCount()>0&&cursor.moveToFirst()) {
do {
events.add(cursor.getString(1));
} while ( cursor.moveToNext());
}
It will give today's event from Calendar content provider.
Note: Managed the deleted events from content provider.
Done
Refer to Calendar Provider Documentation this link
I am using this code and it is working..
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = contentResolver.query(Uri.parse("content://com.android.calendar/calendars"), (new String[] { Calendars._ID, Calendars.ACCOUNT_NAME, Calendars.CALENDAR_DISPLAY_NAME, }), null, null, null);
This methods is 100% worked for me however i tried several method . It will get all the event and store in a set . Then you can check the set whether a event is in the set or not . In this way you can check duplicate event
public Set<String> readCalendarEvent(Context context) {
Cursor cursor = context.getContentResolver()
.query(
Uri.parse("content://com.android.calendar/events"),
new String[] { "calendar_id", "title", "description",
"dtstart", "dtend", "eventLocation" }, null,
null, null);
cursor.moveToFirst();
// fetching calendars name
String CNames[] = new String[cursor.getCount()];
// fetching calendars id
calendars.clear();
Log.d("cnameslength",""+CNames.length);
if (CNames.length==0)
{
Toast.makeText(context,"No event exists in calendar",Toast.LENGTH_LONG).show();
}
for (int i = 0; i < CNames.length; i++) {
calendars.add(cursor.getString(1));
CNames[i] = cursor.getString(1);
cursor.moveToNext();
}
return calendars;
}
try this code i am in my application i am used this event for display event date wise;
ContentResolver contentResolver = mContext.getContentResolver();
final Cursor cursor = contentResolver.query(Uri.parse("content://com.android.calendar/calendars"),
(new String[] { "_id", "displayName", "selected" }), null, null, null);
HashSet<String> calendarIds = new HashSet<String>();
while (cursor.moveToNext()) {
final String _id = cursor.getString(0);
final String displayName = cursor.getString(1);
final Boolean selected = !cursor.getString(2).equals("0");
//System.out.println("Id: " + _id + " Display Name: " + displayName + " Selected: " + selected);
calendarIds.add(_id);
}
in this snipped you should get all calendar event in calendarIds...now check
for (String id : calendarIds) {
Uri.Builder builder = Uri.parse("content://com.android.calendar/instances/when").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=" + id,
null, "startDay ASC, startMinute ASC");
// For a full list of available columns see http://tinyurl.com/yfbg76w
while (eventCursor.moveToNext()) {
eventTitle = eventCursor.getString(0);
begin = new Date(eventCursor.getLong(1));
end = new Date(eventCursor.getLong(2));
allDay = !eventCursor.getString(3).equals("0");
eventDate = begin.getDate();
eventTime = begin.getHours();
eventMonth = begin.getMonth();
eventYear = begin.getYear();
event.add(eventTitle);
SimpleDateFormat sdfcur = new SimpleDateFormat("yyyy-MM-dd");
String beginString = sdfcur.format(begin);
Date begindt = null;
try {
begindt = sdfcur.parse(beginString);
stringEventDate = begindt.getDate();
stringEventMonth = begindt.getMonth();
stringEventYear = begindt.getYear();
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
Date dt = null;
dt = sdfcur.parse(onClickDate);
int passedday=dt.getDate();
int passedmonth = dt.getMonth();
int passedyear = dt.getYear();

Categories

Resources