Android CalendarProvider query provides strange start and end times - android

So when I query the CalendarProvider for a list of events for my personal calendar, I'm getting some really strange start and end times. For example I see a result in the query that is 1970-01-13, but in my Google Calendar app it appears properly as 2015-02-01. All the events I got as a result have strange times like this.
My query is below.
String[] mProjection = new String[]{
Events.CALENDAR_ID,
Events.ORGANIZER,
Events.TITLE,
Events.DTSTART,
Events.DTEND,
Events._ID
};
ContentResolver cr = getActivity().getContentResolver();
Uri uri = Events.CONTENT_URI;
String selection = Events.CALENDAR_ID + " = ?";
String[] selectionArgs = new String[] {"2"};
Cursor cur = cr.query(uri, mProjection, selection, selectionArgs, null);
Log.i(TAG, "events " + cur.getCount());
TextView textView = (TextView) rootView.findViewById(R.id.dummy_text);
while (cur.moveToNext()) {
int calID = cur.getInt(0);
String organizer = cur.getString(1);
String title = cur.getString(2);
int start = cur.getInt(3);
int end = cur.getInt(4);
int event_id = cur.getInt(5);
Calendar startCal = Calendar.getInstance();
startCal.setTimeInMillis(start);
Calendar endCal = Calendar.getInstance();
endCal.setTimeInMillis(end);
Here's my code for converting the times to be readable.
public static String getHumanDate(int year, int month, int dayOfMonth) {
String monthZero = "";
String dayOfMonthZero = "";
if ((month + 1) < 10)
monthZero = "0";
if (dayOfMonth < 10)
dayOfMonthZero = "0";
return year + "-" + monthZero + (month + 1) + "-" + dayOfMonthZero + dayOfMonth;
}

Figured it out. Should have used
long start = cur.getLong(3);
long end = cur.getLong(4);
Rather than int.

Related

date format in sms inbox

I use this code for date in sms inbox but it shows 01/01/70 wrong date for all sms how do I change correct?
public void refreshSmsInbox() {
ContentResolver contentResolver = getActivity().getContentResolver();
Cursor smsInboxCursor = contentResolver.query(Uri.parse("content://sms/inbox"), null, null, null, null);
int indexBody = smsInboxCursor.getColumnIndex("body");
int indexAddress = smsInboxCursor.getColumnIndex("address");
int timeMillis = smsInboxCursor.getColumnIndex("date");
Date date = new Date(timeMillis);
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yy");
String dateText = format.format(date);
if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return;
arrayAdapter.clear();
do {
String str = smsInboxCursor.getString(indexAddress) +" "+
"\n" + smsInboxCursor.getString(indexBody) +"\n"+ dateText+"\n";
arrayAdapter.add(str);
} while (smsInboxCursor.moveToNext());
smsInboxCursor.close();
}
#Mike M's comment was correct. You're trying to convert the index of the date column to Date format. You're not actually converting the value of the date. Try this:
public void refreshSmsInbox() {
ContentResolver contentResolver = getContentResolver();
Cursor smsInboxCursor = contentResolver.query(Uri.parse("content://sms/inbox"), null, null, null, null);
// get the index of the column
int indexBody = smsInboxCursor.getColumnIndex("body");
int indexAddress = smsInboxCursor.getColumnIndex("address");
int indexDate = smsInboxCursor.getColumnIndex("date");
if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return;
// loop through the messages in inbox
do {
// get the value based on the index of the column
String address = smsInboxCursor.getString(indexAddress);
String body = smsInboxCursor.getString(indexBody);
long date = smsInboxCursor.getLong(indexDate);
// convert millis value to proper format
Date dateVal = new Date(date);
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yy");
String dateText = format.format(dateVal);
String str = address + "\n" + body + "\n" + dateText + "\n";
System.out.println(str);
} while (smsInboxCursor.moveToNext());
smsInboxCursor.close();
}
This part is wrong:
int timeMillis = smsInboxCursor.getColumnIndex("date");
Date date = new Date(timeMillis);
getColumnIndex returns an index, not the actual value. I think you want this instead, though I haven't tested it myself:
int dateIndex = smsInboxCursor.getColumnIndex("date");
long timeMillis = smsInboxCursor.getLong(dateIndex);
Date date = new Date(timeMillis);

Account Name in Calendar Android getting gmail automatically

I found this article very useful http://developer.android.com/guide/topics/providers/calendar-provider.html#query?
But here i found the ACCOUNT_NAME queried in the calendar is being written statically
I am stuck here Since my problem is ..what if i want user's gmail address through some query
i.e not statically specifying the address rather getting it through some code
PS: i am very newbie to android. Apologies if this ones a stupid question
long calID = 0;
String displayName = null;
String accountName = null;
String ownerName = null;
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.
final int PROJECTION_ID_INDEX = 0;
final int PROJECTION_ACCOUNT_NAME_INDEX = 1;
final int PROJECTION_DISPLAY_NAME_INDEX = 2;
final int PROJECTION_OWNER_ACCOUNT_INDEX = 3;
// Run query
Cursor cur = null;
ContentResolver cr = app.getContentResolver();
Uri uri = Calendars.CONTENT_URI;
String selection = "((" + Calendars.ACCOUNT_NAME + " = ?) AND ("
+ Calendars.ACCOUNT_TYPE + " = ?) AND ("
+ Calendars.OWNER_ACCOUNT + " = ?))";
String[] selectionArgs = new String[] { "sample#gmail.com",
"com.google", "sample#gmail.com" };
// Submit the query and get a Cursor object back.
cur = cr.query(uri, EVENT_PROJECTION, selection, selectionArgs,
null);
// Use the cursor to step through the returned records
while (cur.moveToNext()) {
// 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);
}
Calendar beginTime = Calendar.getInstance();
Calendar ceaseTime = Calendar.getInstance();
ContentValues cv = new ContentValues();
HashMap<String, String> map = (HashMap<String, String>) params[0];
String startDate[] = map.get("startDate").toString().split("-");
String startTime[] = map.get("startTime").toString().split(":");
long beginMilis=0,ceaseMilis=0;
beginTime.set(Integer.parseInt(startDate[2]),
Integer.parseInt(startDate[1]),
Integer.parseInt(startDate[0]),
Integer.parseInt(startTime[0]),
Integer.parseInt(startTime[1]));
beginMilis = beginTime.getTimeInMillis();
String endDate[] = map.get("endDate").toString().split("-");
String endTime[] = map.get("endTime").toString().split(":");
TimeZone tz = TimeZone.getDefault();
ceaseTime.set(Integer.parseInt(endDate[2]),
Integer.parseInt(endDate[1]),
Integer.parseInt(endDate[0]),
Integer.parseInt(endTime[0]),
Integer.parseInt(endTime[1]));
ceaseMilis = ceaseTime.getTimeInMillis();
cv.put(Events.DTSTART, beginMilis);
cv.put(Events.DTEND, ceaseMilis);
cv.put(Events.TITLE, map.get("title").toString());
cv.put(Events.DESCRIPTION, map.get("description").toString());
cv.put(Events.CALENDAR_ID, String.valueOf(calID));
cv.put(Events.EVENT_TIMEZONE, tz.getDisplayName());
uri = cr.insert(Events.CONTENT_URI, cv);

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.

Android date from calllog results in strange form

I am collecting dates of calls from the Calllog, but there is a problem with the dates. I used simpledateformat to format the numbers, but i get false data: years from 1903 to 1948 and from 1954-2036. This is the code I am using:
final Context context = getApplicationContext();
final String[] projection = null;
final String selection = android.provider.CallLog.Calls.NUMBER + "='+3620455351684'";
final String[] selectionArgs = null;
final String sortOrder = android.provider.CallLog.Calls.DATE + " DESC";
Cursor c = null;
try{
c = context.getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, null, selection, null, sortOrder);
while (c.moveToNext()) {
String callLogID = c.getString(c.getColumnIndex(android.provider.CallLog.Calls._ID));
int numberColumn = c.getColumnIndex(android.provider.CallLog.Calls.NUMBER);
int dateColumn = c.getColumnIndex(android.provider.CallLog.Calls.DATE);
int typeColumn = c.getColumnIndex(android.provider.CallLog.Calls.TYPE);
int outgoingtypeColumn = c.getColumnIndex(android.provider.CallLog.Calls.TYPE + "='2'");
int durationColumn = c.getColumnIndex(android.provider.CallLog.Calls.DURATION);
int person = c.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME);
int duration = c.getInt(durationColumn);
int callDate = c.getInt(dateColumn);
int callType = c.getInt(typeColumn);
String number = c.getString(numberColumn);
String personname = c.getString(person);
SimpleDateFormat datePattern = new SimpleDateFormat ("yyyy-MM-dd");;
datePattern.setTimeZone(TimeZone.getTimeZone("GMT"));
String date_str = datePattern.format(new Date(callDate*1000L));
arr_allcallsduration.add(Integer.toString(duration));
arr_calls.add(Integer.toString(duration) + " : " + number + " : " + date_str);
}
}catch(Exception ex){
}finally{
c.close();
}
Output:
56 : +3620455351684 : 1948-08-02
425 : +3620455351684 : 1947-06-17
337 : +3620455351684 : 1947-06-13
etc.
I found the solution. The callDate should be declared as long:
long callDate = c.getLong(dateColumn);
One other modification:
String date_str = datePattern.format(new Date(callDate));
Hope this helps others!

Categories

Resources