How to read events for a particular date from native calendar - android

Im trying to read native calender events from my app(ICS and above) but sometimes it works and some times it shows some incorrect values.Currently i'm using this piece of code can anyone please tell me where i'm going wrong..
Uri.Builder builder = Uri.parse("content://com.android.calendar/instances/when").buildUpon();
long now = new Date().getTime();
ContentUris.appendId(builder, now);
ContentUris.appendId(builder, now + DateUtils.YEAR_IN_MILLIS);
Cursor eventCursorr = cr.query(builder.build(),
new String[] { "title", "begin","description"}, "Calendars._id=" + calID,
null, "startDay ASC, startMinute ASC");
while (eventCursorr.moveToNext()) {
final String titler = eventCursorr.getString(0).trim();
final Date beginr = new Date(eventCursorr.getLong(1));
final String descriptionr = eventCursorr.getString(2).trim();
SimpleDateFormat sdfrr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String stimesr = sdfrr.format(beginr);
System.out.println("titler "+titler +"stimesr "+stimesr +"descriptionr "+descriptionr );
}
}

i solved it guys.
//StartTime
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
Date dateCC = formatter.parse("04/27/2013");
Calendar calendarStartDate = Calendar.getInstance();
calendar.setTime(dateCC);
//EndTime
SimpleDateFormat formatterr = new SimpleDateFormat("MM/dd/yy hh:mm:ss");
Calendar endOfDay = Calendar.getInstance();
Date dateCCC = formatterr.parse("04/27/2013 23:59:59");
endOfDay.setTime(dateCCC);
Cursor eventCursorr = cr.query(l_eventUri,
new String[] {
"title", "dtstart", "dtend"
}, "(" + dtstart + ">" + after + " and " + dtend + "<" + endOfDay.getTimeInMillis() + ")",
null, "dtstart ASC");
while (eventCursorr.moveToNext()) {
final String titler = eventCursorr.getString(0).trim();
final Date beginr = new Date(eventCursorr.getLong(1));
final String descriptionr = eventCursorr.getString(2).trim();
}

Related

how to convert android contacts date-of birth-string to date format?

In my Android project i want to convert contacts date-of-birth as string to date from user locale.
String whereBday = ContactsContract.Data.MIMETYPE + "= ? AND " +
ContactsContract.CommonDataKinds.Event.TYPE + "=" +
ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
String[] paramsBday = new String[]{
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE };
Cursor bDayCursor = contentResolver.query(ContactsContract.Data.CONTENT_URI,
null, whereBday, paramsBday, null);
while (bDayCursor.moveToNext()) {
//date of birth as String format
String bDay = bDayCursor.getString(bDayCursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
//converting string to date format
SimpleDateFormat formatter = new SimpleDateFormat(bDay);
Date myDate= formatter.parse(mytime);
DateFormat f = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault());
String formattedDate = f.format(new Date());
System.out.println("Date: " + formattedDate);
}
bDayCursor.close();
Unfortunately it seems that there is no fixed standard as to what the date format is stored in. The best solution is to loop through a list of date formats, and see if it matches any of the following. And once you get the date object you can modify it to be printed in any format using your own formatter. Also if its not found, then you can check the format which is not supported, and add it in your array.
You can use the following code:
public static final SimpleDateFormat[] birthdayFormats = {
new SimpleDateFormat("yyyy-MM-dd"),
new SimpleDateFormat("yyyy.MM.dd"),
new SimpleDateFormat("yy-MM-dd"),
new SimpleDateFormat("yy.MM.dd"),
new SimpleDateFormat("yy/MM/dd"),
new SimpleDateFormat("MMM dd, yyyy")
};
private void printBirthdays() {
Cursor cursor = getContactsBirthdays();
int bDayColumn = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE);
while (cursor.moveToNext()) {
String bDay = cursor.getString(bDayColumn);
Date birthday = null;
boolean found = false;
for (SimpleDateFormat f : birthdayFormats) {
try {
birthday = f.parse(bDay);
Log.e(TAG, bDay + " = " + birthday.toString());
found = true;
break;
} catch (ParseException e) {
}
}
if (!found) {
Log.e(TAG, bDay);
}
}
}
private Cursor getContactsBirthdays() {
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;
return managedQuery(uri, projection, where, selectionArgs, sortOrder);
}

Days get only past 7 days data in List android-sqlite

I have created an app that uses Sqlite database. I want to display the data from today to 7 days past. Data above that should not be selected. So for that I had written a query, but it doesn't seem to be working. In the list I am getting data above past 7 days also
Code
public ArrayList<DbModel> getRecentDocs() {
database = getWritableDatabase();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String todate = dateFormat.format(date);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -7);
Date todate1 = cal.getTime();
String fromdate = dateFormat.format(todate1);
alGetRecentFiles = new ArrayList<DbModel>();
dbModel = new DbModel();
String query = "Select * From " + saveFileTable + " where " + postedOn + " >= " + fromdate;
Cursor c = database.rawQuery(query, null);
while (c.moveToNext()) {
dbModel = new DbModel(c.getString(c.getColumnIndexOrThrow(userId)), c.getString(c.getColumnIndexOrThrow(docId)), c.getString(c.getColumnIndexOrThrow(fileName)), c.getString(c.getColumnIndexOrThrow(fileExt)), c.getString(c.getColumnIndexOrThrow(title)), c.getString(c.getColumnIndexOrThrow(filePath)), c.getString(c.getColumnIndexOrThrow(postedOn)), c.getString(c.getColumnIndexOrThrow(favourite)));
alGetRecentFiles.add(dbModel);
}
c.close();
database.close();
return alGetRecentFiles;
}

How to get the Event instance from android calender api?

i am trying to get the id of an instance of recurring event, i am doing this task like this
final String[] INSTANCE_PROJECTION = new String[] {
Instances.EVENT_ID, // 0
Instances.BEGIN, // 1
Instances.TITLE // 2
};
Calendar beginTime = Calendar.getInstance();
beginTime.set(2011, 9, 23, 8, 0);
long startMillis = beginTime.getTimeInMillis();
Calendar endTime = Calendar.getInstance();
endTime.set(2011, 10, 24, 8, 0);
long endMillis = endTime.getTimeInMillis();
Cursor cur = null;
ContentResolver cr = view.getContext().getContentResolver();
String selection = Instances.EVENT_ID + " = ?";
String[] selectionArgs = new String[] {"207"};
Uri.Builder builder = Instances.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, startMillis);
ContentUris.appendId(builder, endMillis);
final int PROJECTION_ID_INDEX = 0;
final int PROJECTION_BEGIN_INDEX = 1;
final int PROJECTION_TITLE_INDEX = 2;
cur = cr.query(builder.build(),
INSTANCE_PROJECTION,
selection,
selectionArgs,
null);
while (cur.moveToNext()) {
String title = null;
long eventID = 0;
long beginVal = 0;
// Get the field values
eventID = cur.getLong(PROJECTION_ID_INDEX);
beginVal = cur.getLong(PROJECTION_BEGIN_INDEX);
title = cur.getString(PROJECTION_TITLE_INDEX);
// Do something with the values.
//Log.i(DEBUG_TAG, "Event: " + title);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(beginVal);
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
//Log.i(DEBUG_TAG, "Date: " + formatter.format(calendar.getTime()));
Toast.makeText(view.getContext(), "Date: " + formatter.format(calendar.getTime()), Toast.LENGTH_SHORT).show();
but it is not working, i don't understand where did i go wrong. if anyone gets the problem please let me know.
I have done it sucessfully, now I am able to get an instance.. here is a code:
final String[] INSTANCE_PROJECTION = new String[] {
Instances.EVENT_ID, // 0
Instances.BEGIN, // 1
Instances.TITLE // 2
};
Calendar beginTime = Calendar.getInstance();
beginTime = selectedAppointmentInstance.getStartDate();
long startMillis = beginTime.getTimeInMillis();
Calendar endTime = Calendar.getInstance();
endTime = selectedAppointmentInstance.getEndDate();
long endMillis = endTime.getTimeInMillis()-1;
Cursor cur = null;
ContentResolver cr = view.getContext().getContentResolver();
String selection = Instances.EVENT_ID + " = ?" ;
String[] selectionArgs = new String[] {selectedAppointmentInstance.getAppointmentId()};
Uri.Builder builder = Instances.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, startMillis);
ContentUris.appendId(builder, endMillis);
String where=Instances.EVENT_ID + " = " + selectedAppointmentInstance.getAppointmentId();
final int PROJECTION_ID_INDEX = 0;
final int PROJECTION_BEGIN_INDEX = 1;
final int PROJECTION_TITLE_INDEX = 2;
cur = cr.query(builder.build(),
INSTANCE_PROJECTION,
selection,
selectionArgs,
null);
while (cur.moveToNext()) {
String title = null;
long eventID = 0;
long beginVal = 0;
// Get the field values
eventID = cur.getLong(PROJECTION_ID_INDEX);
beginVal = cur.getLong(PROJECTION_BEGIN_INDEX);
title = cur.getString(PROJECTION_TITLE_INDEX);
// Do something with the values.
//Log.i(DEBUG_TAG, "Event: " + title);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(beginVal);
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
//Log.i(DEBUG_TAG, "Date: " + formatter.format(calendar.getTime()));
Toast.makeText(view.getContext(), "Date: " + formatter.format(calendar.getTime()), Toast.LENGTH_SHORT).show();
}

Reading browsing date and time in Android

I am using the code below to access browser's history in Title, Url, Date and Time format; Title and Url works fine but while accessing Date and time it gives a long integer value. Can anyone suggest what changes I need to make in order to properly get the date and time?
String sel = Browser.BookmarkColumns.BOOKMARK + " = 0";
Cursor mCur = managedQuery(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, sel, null, null);
j = mCur.getCount();
String[] mTitles = new String[j];
String[] murls = new String[j];
long[] date=new long[j];
mCur.moveToFirst();
i=j-1;
if (mCur.moveToFirst() && mCur.getCount() > 0) {
int titleIdx = mCur.getColumnIndex(Browser.BookmarkColumns.TITLE);
int urlIdx = mCur.getColumnIndex(Browser.BookmarkColumns.URL);
int dateIdx=mCur.getColumnIndex(Browser.BookmarkColumns.DATE);
while (mCur.isAfterLast() == false ) {
mTitles[i]=mCur.getString(titleIdx);
murls[i]=mCur.getString(urlIdx);
date[i]=mCur.getLong(dateIdx);
i--;
mCur.moveToNext();
}
}
// using Calendar class
Calendar ci = Calendar.getInstance();
String CiDateTime = "" + ci.get(Calendar.YEAR) + "-" +
(ci.get(Calendar.MONTH) + 1) + "-" +
ci.get(Calendar.DAY_OF_MONTH) + " " +
ci.get(Calendar.HOUR) + ":" +
ci.get(Calendar.MINUTE) + ":" +
ci.get(Calendar.SECOND);
and to get it in a formate you can try this.
SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
otherwise you can use Time class , it's a faster implementation of Calendar class
http://developer.android.com/reference/android/text/format/Time.html
The Date should be a long, since it is the number of milliseconds since January 1, 1970. An integer would be too short.

Get calendar events for ICS android version 4 for a particular date

I m tring to display the calendar events in android version 4 which can give the arraylist for the title and other details for the events like this but unable to display.
I get the error as calendar not found.
public void readCalendar1()
{
ContentResolver contentResolver = this.getContentResolver();
// Fetch a list of all calendars synced with the device, their display names and whether the
// user has them selected for display.
Cursor cursor;
cursor = contentResolver.query(CalendarContract.Calendars.CONTENT_URI, new String[]
{ CalendarContract.Calendars._ID, CalendarContract.Calendars.CALENDAR_DISPLAY_NAME },
null, null, CalendarContract.Calendars.CALENDAR_DISPLAY_NAME + " ASC");
HashSet<String> calendarIds1 = new HashSet<String>();
while (cursor.moveToNext())
{
final String _id = cursor.getString(0);
final String displayName = cursor.getString(1);
System.out.println("Id: " + _id + " Display Name: " + displayName );
calendarIds1.add(_id);
}
// For each calendar, display all the events from the previous week to the end of next week.
for (String id : calendarIds1)
{
Uri builder = CalendarContract.Events.CONTENT_URI;
System.out.println("str in read cal1 "+strconvert+"str2 in read cal1 "+strconvert1);
//strconvert and strconvert1 are string which have the particular dates
Cursor eventCursor = contentResolver.query(builder,
new String[] { CalendarContract.Events.TITLE, strconvert,
strconvert1, CalendarContract.Events.ALL_DAY,CalendarContract.Events.EVENT_LOCATION,
CalendarContract.Events.HAS_ALARM,CalendarContract.Events.DESCRIPTION},
"calendar_id=" + id,null,"dtstart ASC" );
// For a full list of available columns see http://tinyurl.com/yfbg76w
int n=eventCursor.getCount();
System.out.println("No. of rows is="+n);
while(eventCursor.moveToNext())
{
title = eventCursor.getString(0);
begin = new Date(eventCursor.getLong(1));
end = new Date(eventCursor.getLong(2));
allDay = !eventCursor.getString(3).equals("0");
loc=eventCursor.getString(4);
hasalarm = !eventCursor.getString(5).equals("0");
desc=eventCursor.getString(6);
titlestr.add(title);
sdatestr.add(begin.toString());
edatestr.add(end.toString());
locstr.add(loc);
descstr.add(desc);
alarmstr.add(hasalarm.toString());
System.out.println("Title String: " + titlestr);
System.out.println("Begin String: " + sdatestr);
System.out.println("End String: " + edatestr);
System.out.println("Loc String: " + locstr);
System.out.println("Desc String: " + descstr);
System.out.println("Alarm String: " + alarmstr);
// }
System.out.println("Title: " + title + " Begin: " + begin + " End: " + end +
" All Day: " + allDay+" Location="+loc+" Descriptn="+desc);
}
}
}
This code is working for me to read for both versions below ics android 4 and above ics
//for os version android bELOW version 4(ICS)
public static boolean eventChecker(Context context,ContentResolver cr,String calID){
Uri.Builder builder = Uri.parse("content://com.android.calendar/instances/when").buildUpon();
long now = new Date().getTime();
ContentUris.appendId(builder, now);
ContentUris.appendId(builder, now + DateUtils.YEAR_IN_MILLIS);
Cursor eventCursorr = cr.query(builder.build(),
new String[] { "title", "begin","description"}, "Calendars._id=" + calID,
null, "startDay ASC, startMinute ASC");
while (eventCursorr.moveToNext()) {
final String titler = eventCursorr.getString(0).trim();
final Date beginr = new Date(eventCursorr.getLong(1));
final String descriptionr = eventCursorr.getString(2).trim();
SimpleDateFormat sdfrr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String stimesr = sdfrr.format(beginr);
System.out.println("titler "+titler +"stimesr "+stimesr +"descriptionr "+descriptionr );
}
}
//for os version android version 4(ICS) AND ABOVE
#TargetApi(14)
public static boolean eventChecker14(Context context,ContentResolver contentResolver,String calID){
Uri builder = CalendarContract.Events.CONTENT_URI;
String[] COLS = new String[]{ CalendarContract.Events.TITLE, CalendarContract.Events.DTSTART,CalendarContract.Events.DESCRIPTION};
Cursor eventCursor = contentResolver.query(builder,
COLS,
"calendar_id=" + calID,null,"dtstart ASC" );
int n=eventCursor.getCount();
System.out.println("No. of rows is="+n);
while(eventCursor.moveToNext())
{
String title1 = eventCursor.getString(0).trim();
Date begin1 = new Date(eventCursor.getLong(1));
String desc1=eventCursor.getString(2).trim();
SimpleDateFormat sdfrr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String stimesr = sdfrr.format(begin1);
System.out.println("title1"+title1+"desc1"+desc1+"stimesr"+stimesr);
}
}

Categories

Resources