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();
Related
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
}
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);
Here is my code:
private void readSMS() throws IOException {
// TODO Auto-generated method stub
Log.d("Read SMS","Called");
ContentResolver cr = context.getContentResolver();
Uri uri = Uri.parse("content://sms/inbox");
String smsBackup;
Cursor messagesCursor = cr.query(uri, new String[] { "_id","address","body","person"}, null,null, null);
smsBackup = "SMS Back UP (Total Message(s)::"+messagesCursor.getCount()+") \n\n";
String smsfile = "SMS" + "_" + System.currentTimeMillis()+".txt";
storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + smsfile;
FileOutputStream mFileOutputStream = new FileOutputStream(storage_path,true);
mFileOutputStream.write(smsBackup.getBytes());
String name = null,smsString;
int smsCounter = 1;
if(messagesCursor.getCount() > 0){
while(messagesCursor.moveToNext()){
name = null;
name = getName(messagesCursor.getString(messagesCursor.getColumnIndex("address")));
if(name==null)
name = "Sender : " + messagesCursor.getString(messagesCursor.getColumnIndex("address"));
smsString = "SMS No : "+smsCounter+"\nSender : "+name +"\n"+ "Message : "+messagesCursor.getString(messagesCursor.getColumnIndex("body")) + "\n\n";
mFileOutputStream.write(smsString.getBytes());
Log.d("Message","::"+smsString+"Length::"+smsString.length());
smsString = null;
Log.d("Message","written::"+smsCounter);
smsCounter++;
}
messagesCursor.close();
file = new File(storage_path);
mFileOutputStream.close();
Log.d("MSGFile","written");
}
}
private String getName(String number1) {
// TODO Auto-generated method stub
Log.d("get name","Called");
//Log.d("get name",number1);
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
if(cur.getCount() > 0){
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
Cursor names = getContentResolver().query(uri, projection, null, null, null);
int indexName = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
names.moveToFirst();
do {
String name = names.getString(indexName);
//Log.e("Name new:", name);
String number = names.getString(indexNumber);
//Log.e("Number new:","::"+number);
if(number1.contains(number)){
cur.close();
return name;
}
} while (names.moveToNext());
}
cur.close();
return null;
}
I am getting warning also : W/CursorWrapperInner(22787): Cursor finalized without prior close()
use the bellow code get the contacts
private void readMessagesFromDeviceDB()
{
Uri SMSURI = Uri.parse("content://sms/inbox");
String[] projection = new String[]{"_id", "address", "body", "date"};
Cursor cursor = null;
try
{
cursor = getContentResolver().query(SMSURI
, projection
, null //selection
, null //selectionArgs
, null); //sortOrder
if (cursor != null && cursor.moveToFirst())
{
do
{
int id = cursor.getInt(cursor.getColumnIndex("_id")); //returns a unique thread id
String address = cursor.getString(cursor.getColumnIndex("address")); //returns contact no.
String body = cursor.getString(cursor.getColumnIndex("body")); //returns message body
String date = cursor.getString(cursor.getColumnIndex("date")); //returns date( when was the message received )
SimpleDateFormat formatter = new SimpleDateFormat("dd, MMM HH:mm");
date = formatter.format(new Date(Long.parseLong(date)));
// System.out.println("id: " + id + " address: " + address + " body: " + body + " date: " + date);
}
while (cursor.moveToNext());
}
} finally {
if (cursor != null)
{
cursor.close();
}
}
}
I am using below code to get and load calendar events in my application. It's working perfectly. But now i want to get events specified date range. How can i get it..
Cursor cursor = getContentResolver().query(
Uri.parse("content://com.android.calendar/events"),
new String[] { "_id", "title", "dtstart", "dtend" }, null,
null, "dtstart ASC");
should be
dtstart = "2013-01-01"
dtend= "2013-01-31"
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 };
// 0 = January, 1 = February, ...
Calendar startTime = Calendar.getInstance();
startTime.set(2014,00,01,00,00);
Calendar endTime= Calendar.getInstance();
endTime.set(2015,00,01,00,00);
// the range is all data from 2014
String selection = "(( " + CalendarContract.Events.DTSTART + " >= " + startTime.getTimeInMillis() + " ) AND ( " + CalendarContract.Events.DTSTART + " <= " + endTime.getTimeInMillis() + " ))";
Cursor cursor = this.getBaseContext().getContentResolver().query( CalendarContract.Events.CONTENT_URI, projection, selection, null, null );
// output the events
if (cursor.moveToFirst()) {
do {
Toast.makeText( this.getApplicationContext(), "Title: " + cursor.getString(1) + " Start-Time: " + (new Date(cursor.getLong(3))).toString(), Toast.LENGTH_LONG ).show();
} while ( cursor.moveToNext());
}
This was what I implemented to retrieve the events:
if (Integer.parseInt(Build.VERSION.SDK) >= 8 || Integer.parseInt(Build.VERSION.SDK) <= 13 ) {
uri = "content://com.android.calendar/events";
CALENDAR_URI = Uri.parse(uri);
} else if(Integer.parseInt(Build.VERSION.SDK) >= 14){
CALENDAR_URI = CalendarContract.Events.CONTENT_URI;
}
else {
uri = "content://calendar/events";
CALENDAR_URI = Uri.parse(uri);
}
Cursor cursors = context.getContentResolver().query(CALENDAR_URI, new String[]{ "_id", "title", "description", "dtstart", "dtend", "eventLocation" },
null,null, null);
cursors.moveToFirst();
String[] CalNames = new String[cursors.getCount()];
int[] CalIds = new int[cursors.getCount()];
for (int i = 0; i < CalNames.length; i++) {
CalIds[i] = cursors.getInt(0);
CalNames[i] = "Event"+cursors.getInt(0)+": \nTitle: "+ cursors.getString(1)+"\nDescription: "+cursors.getString(2)+"\nStart Date: "+new Date(cursors.getLong(3))+"\nEnd Date : "+new Date(cursors.getLong(4))+"\nLocation : "+cursors.getString(5);
Date mDate = new Date(cursors.getLong(3));
Date nDate = new Date(cursors.getLong(4));
long mTime = mDate.getTime();
long lTime = nDate.getTime();
if(stTime <= mTime && enTime >= lTime){
String eid = cursors.getString(0);
int eID = Integer.parseInt(eid);
String desc = cursors.getString(2);
String title = cursors.getString(1);
In this case your stTime will be yo dtstart and enTime will be your dtend.
I am trying to birthday information to a contact. I use lookupkey to identify my contacts (as it is safer than just relying on contactId). In order to be able to insert the Event into the database i need a raw_contact_id ... so i'm trying to get this id:
String where = ContactsContract.Data.LOOKUP_KEY + " = ? AND "
+ ContactsContract.Data.MIMETYPE + " = ?";
String[] params = new String[] { lookupKey,
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE };
Cursor cursor = contentResolver.query(
ContactsContract.Data.CONTENT_URI, null, where, params, null);
if (cursor.moveToFirst()) {
birthdayRow = cursor.getInt(idIdx);
long rawContactId = cursor.getLong(cursor
.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
}
The problem is that if there is not birthday event set for a contact then this cursor i receive is empty ... and i don't know how to insert this event without a raw_contact_id. In order to insert the event i do the folowing:
values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
values.put(ContactsContract.Data.MIMETYPE, Event.CONTENT_ITEM_TYPE);
values.put(ContactsContract.CommonDataKinds.Event.START_DATE,
birthdayStartDate);
values.put(ContactsContract.CommonDataKinds.Event.TYPE,
ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY);
values.put(ContactsContract.CommonDataKinds.Event.START_DATE,
context.getString(R.string.birthday_label));
if (birthdayRow >= 0) {
int result = contentResolver.update(
ContactsContract.Data.CONTENT_URI, values,
ContactsContract.Data._ID + " = " + birthdayRow, null);
Log.i("ContactList", "update result: " + result);
} else {
Uri result = contentResolver.insert(
ContactsContract.Data.CONTENT_URI, values);
Log.i("ContactList", "update result: " + result);
}
So please advice what shall i do, is there any way to add this event to the ContactData whitout a raw_contact id? Also i find strange the fact that for other ContactData like nickname i am doing the same thing and i dont get an empty cursor for the params
String[] params = new String[] { String.valueOf(lookupKey),
ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE };
even if the contact has no nickname.
Use this to get the raw contact id before performing the insert.
long rawContactId = -1;
String[] projection = new String[]{ContactsContract.CommonDataKinds.Event.RAW_CONTACT_ID};
String selection = ContactsContract.CommonDataKinds.Event.CONTACT_ID + "=?";
String[] selectionArgs = new String[]{
String.valueOf(bdayContact.getId()) };
Cursor c = getContentResolver().query(ContactsContract.Data.CONTENT_URI, projection, selection, selectionArgs, null);
try {
if (c.moveToFirst()) {
rawContactId = c.getLong(0);
}
} finally {
c.close();
}