I am trying to add Events in my app using a calender.According to CalenderContract,I need to provide a constant ID each time I add an event to the calender.I don't know how to do that.
I tried using calender_ID =1 which worked on some devices and calender_ID = 3 which also worked on some devices.
I think there would be some default ID which can be used to make this work properly.
Can anyone please tell me how this can be done?
Thanks in Advance.
you can get the calender id by this following code :
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();
}
So you can get the calender Id at runtime and use it . you don't need hardcoded 1 or 3 column Id.
Related
I am trying to get contactId of newly added contact programmatically. Contact is being added successfully and fetches the contactID from ContentProviderResult[] but contactId which I am getting is not the correct one. I have also seen this and this answer but contactId is not the correct one. Here is my code
ArrayList<ContentProviderOperation> contentProviderOperation = new ArrayList<>();
......
......
ContentProviderResult[] results = getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, contentProviderOperation);
long contactId = ContentUris.parseId(results[0].uri);
I have also tried the below code:
ContentProviderResult[] results = getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, contentProviderOperation);
Uri myContactUri = results[0].uri;
int lastSlash = myContactUri.toString().lastIndexOf("/");
int length = myContactUri.toString().length();
int contactID = Integer.parseInt((String) myContactUri.toString().subSequence(lastSlash+1, length));
But the contactId I am getting here is not the correct one. Please Correct me if I am going something wrong. Thanks in advance.
After working regularly I have find a way to find out the correct contactId by the following code:
public static int getContactIDFromNumber(String contactNumber, Context context) {
contactNumber = Uri.encode(contactNumber);
int phoneContactID = new Random().nextInt();
Cursor contactLookupCursor = context.getContentResolver().query(Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, contactNumber), new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID}, null, null, null);
while (contactLookupCursor.moveToNext()) {
phoneContactID = contactLookupCursor.getInt(contactLookupCursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
}
contactLookupCursor.close();
return phoneContactID;
}
Pass the contactId of newly added contact that is present in an arrayList.
I know this is not the correct way to find the contact. But it works for me.
I've been trying to figure out how to develop a requirement of one of my projects. The requirement is to get information about phone calls:
Timestamp and phone number of ingoing/outgoing calls
Timestamp and reason of finished call (call ended by user, network unreachable...)
What I found until now is not so much. This next link
http://developer.android.com/reference/android/telephony/PhoneStateListener.html
Talks about creating a listener to get incoming calls phone number.
Anyone can help me with the rest of functionality? where to get the outgoing information of phone calls? Is there any way to know when a phone call is finished, and the reason?
Thank you in advance,
private void getCallLogDetail( Context context ) {
String[] projection = new String[] {
BaseColumns._ID,
CallLog.Calls.NUMBER,
CallLog.Calls.TYPE,
CallLog.Calls.DURATION
};
ContentResolver resolver = context.getContentResolver();
Cursor cur = resolver.query(
CallLog.Calls.CONTENT_URI,
projection,
null,
null,
CallLog.Calls.DEFAULT_SORT_ORDER );
if( !cur.isAfterLast()) {
int numberColumn = cur.getColumnIndex( CallLog.Calls.NUMBER );
int typeColumn = cur.getColumnIndex( CallLog.Calls.TYPE );
int durationcolumn = cur.getColumnIndex(CallLog.Calls.DURATION);
String number = cur.getString( numberColumn );
String type = cur.getString( typeColumn );
String duration = cur.getString(durationcolumn);
cur.moveToNext();
}
}
I'm trying to write a class to add events to a user's calendar in the background (not using intents). I need to ultimately be able to add as many as 7 events in a loop, so I can't do this with the approach where we turn control over to the calendar for the user to confirm.
Unfortunately, I'm not getting anywhere. The only feedback that I get from the logcat is a warning: Cursor finalized without prior close()
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class AddToCalendar {
Context context;
// 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
};
// The indices for the projection array above.
private static final int PROJECTION_ID_INDEX = 0;
private static final int PROJECTION_ACCOUNT_NAME_INDEX = 1;
private static final int PROJECTION_DISPLAY_NAME_INDEX = 2;
private static final int PROJECTION_OWNER_ACCOUNT_INDEX = 3;
public AddToCalendar (Context context) {
this.context = context;
}
public Cursor getCalendars() {
Cursor cursor = null;
ContentResolver cr = context.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.
cursor = cr.query(uri, EVENT_PROJECTION, selection, selectionArgs, null);
return cursor;
}
public void addEvent(Cursor cursor, String type, String location, String description, Date workout_date) {
System.err.println("adding event");
while (cursor.moveToNext()) {
String displayName = null;
String accountName = null;
String ownerName = null;
// Get the field values
long calID = 0;
calID = cursor.getLong(PROJECTION_ID_INDEX);
displayName = cursor.getString(PROJECTION_DISPLAY_NAME_INDEX);
accountName = cursor.getString(PROJECTION_ACCOUNT_NAME_INDEX);
ownerName = cursor.getString(PROJECTION_OWNER_ACCOUNT_INDEX);
System.err.printf("Calendar: %s\n", displayName);
long startMillis = 0;
long endMillis = 0;
Calendar beginTime = Calendar.getInstance();
beginTime.set(2014, 1, 26, 7, 30);
startMillis = beginTime.getTimeInMillis();
Calendar endTime = Calendar.getInstance();
endTime.set(2014, 1, 26, 8, 45);
endMillis = endTime.getTimeInMillis();
ContentResolver cr = context.getContentResolver();
ContentValues values = new ContentValues();
values.put(Events.DTSTART, startMillis);
values.put(Events.DTEND, endMillis);
values.put(Events.TITLE, type);
values.put(Events.EVENT_LOCATION, location);
values.put(Events.DESCRIPTION, description);
values.put(Events.CALENDAR_ID, calID);
values.put(Events.EVENT_TIMEZONE, "America/Los_Angeles");
cr.insert(Events.CONTENT_URI, values);
}
}
}
Most of this is pulled together from http://developer.android.com/guide/topics/providers/calendar-provider.html but it's just not working. Other than the warning that I mentioned, it all "appears" to work, except for the minor detail that nothing shows up on the calendar.
How do I write the getCalendars() query in a general way to get all of the calendars that might be on a user's device? Right now, you can see that I still have the language from the android site.
Any help is appreciated. Thank you.
EDIT: Andrew T pointed out that I have an off-by-one error since the months are zero-based, so I changed my hard coded date to be month 0. I also added a cursor.close() after my while loop. However, I still didn't have anything on my calendar.
One thing that I noticed was that I wasn't entering the while loop. So I took out the loop. When I hard-code the calID variable to 1, I finally get a calendar entry, but this concerns me. I thought that the point of getting the calendars was that a user might use multiple calendars on their device, and the cursor was a way of iterating over each of these calendars. Am I wrong about that?
If hardcoding calID to 1 will solve my problem, I'm fine with that, but I want to make sure that I understand this and am not relying on an ad hoc solution. Thanks again!
The warning is caused by not closing the Calendar Cursor after inserting the events. Call cursor.close() to close it.
Also, have you checked the events on February? I'm afraid you have off-by-1 issue with how month works in Java's Calendar. (Month starts with 0, which is Calendar.JANUARY)
EDIT :
It seems that there is a problem with getCalendars(), particularly on String selection = ... which returns empty Cursor. Also, with this approach, there is a possibility that the event will be added to multiple calendars, which might not be desired.
My idea is to create a ListActivity to list all calendars to let user chooses which calendar he wants to use. With this, you can also save the calendar ID to SharedPreference and use it when creating event conveniently.
I think you can use cursor = cr.query(uri, EVENT_PROJECTION, null, null, null); to list all calendars on the device.
I have added a new Calendar :
ContentValues event2= new ContentValues();
event.put("name", "My calendar");
event.put("displayName", "My new calendar");
event.put("hidden",0);
Uri url2 = getContentResolver().insert(calendarUri, event);
When I list all calendars , the new calendar appears but my native Calendar APP crash and now I can't the new calendar !I have searched here and I tested some ways :
Uri uri1=ContentUris.withAppendedId(calendarUri, calId);
int url3 = getContentResolver().delete(uri1,"_id="+calId",projection);
int url2 = getContentResolver().delete(calendarUri,"_id=3",projection);
But always shows the error: the name must no be empty :null ( the projection is a Array string with id and name)
Any idea?
Might be a bit late but :
Uri evuri = CalendarContract.Calendars.CONTENT_URI;
//substitue your calendar id into the 0
long calid = 0;
Uri deleteUri = ContentUris.withAppendedId(evuri, calid);
getActivity().getContentResolver().delete(deleteUri, null, null);
works for me.
Or if you don't know your calendar id :
Uri evuri = CalendarContract.Calendars.CONTENT_URI;
Cursor result = getActivity().getContentResolver().query(evuri, new String[] {CalendarContract.Calendars._ID, CalendarContract.Calendars.ACCOUNT_NAME, CalendarContract.Calendars.CALENDAR_DISPLAY_NAME}, null, null, null);
while (result.moveToNext())
{
if(result.getString(2).equals("YOUR CALENDAR NAME"))
{
long calid = result.getLong(0);
Uri deleteUri = ContentUris.withAppendedId(evuri, calid);
getActivity().getContentResolver().delete(deleteUri, null, null);
}
}
Of course, finding CalendarContract.Calendars.ACCOUNT_NAME may be redundant for you so just remove it. (there's barely any overhead really)
Try this:
getContentResolver.delete(ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI,
id), null, null);
Where id is the id of the calendar you'd like to delete.
Haven't tested it, but works for events.
I found a lot of question or tutorial about that but no one could work for me.
So i will appreciate if someone can give me a complete solution on How to Delete all my event from my calendar
Thanks for Helping!!!!
There is no calendar in the Android OS.
If you are referring to your Google Calendar, use the Google Calendar GData APIs.
try this it ll help u
if ur device is less than 2.1 mean u use below uri
uri="content://calendar/events"
greeater than 2.1 mean
uri="content://com.android.calendar/events"
Cursor cursor=getContentResolver().query(Uri.parse(uri), null, null, null, null);
cursor.moveToFirst();
// fetching calendars id
if(cursor.getcount>0)
{
CId = new int[cursor.getCount()];
int i=0;
while(!cursor.isAfterLast())
{
CId[i] = cursor.getInt(cursor.getColumnIndex("_id"));
i++;
cursor.moveToNext();
}
delete a calender event
for (int i = 0; i < CNames.length; i++)
{
Uri CALENDAR_URI = Uri.parse(uri);
Uri uri = ContentUris.withAppendedId(CALENDAR_URI,Cid[i]);
getContentResolver().delete(uri, null, null);
}
A shorter way:
Uri eventUri = Uri.parse("content://calendar/events"); // or "content://com.android.calendar/events"
Cursor cursor = contentResolver.query(eventUri, new String[]{"_id"}, "calendar_id = " + calendarId, null, null); // calendar_id can change in new versions
while(cursor.moveToNext()) {
Uri deleteUri = ContentUris.withAppendedId(eventUri, cursor.getInt(0));
contentResolver.delete(deleteUri, null, null);
}