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!
Related
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);
I rarely get following error:
Couldn't read row 439, col 60 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.os.Parcel.readException(Parcel.java:1433)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:185)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:137)
at android.database.BulkCursorProxy.getWindow(BulkCursorNative.java:164)
at android.database.BulkCursorToCursorAdaptor.onMove(BulkCursorToCursorAdaptor.java:83)
at android.database.AbstractCursor.moveToPosition(AbstractCursor.java:214)
at android.database.AbstractCursor.moveToNext(AbstractCursor.java:245)
at android.database.CursorWrapper.moveToNext(CursorWrapper.java:166)
at ....UpdatePhoneContactsJob.h(UpdatePhoneContactsJob.java:64)
The error line corresponds to while (cursor.moveToNext())... I use following function:
Cursor cursor = MainApp.get().getContentResolver().query(
ContactsContract.Data.CONTENT_URI,//ContactsContract.CommonDataKinds.Phone.CONTENT_URI
null,
null,//Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'",
null,
ContactsContract.Data.CONTACT_ID + " ASC");
int rawId = cursor.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID);
int id = cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID);
int lookupKey = cursor.getColumnIndex(ContactsContract.Data.LOOKUP_KEY);
// int photoUri = cursor.getColumnIndex(ContactsContract.Data.PHOTO_URI);
int photoId = cursor.getColumnIndex(ContactsContract.Data.PHOTO_ID);
int name = cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME);
int accountType = cursor.getColumnIndex(ContactsContract.Data.ACCOUNT_TYPE_AND_DATA_SET);
int number = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int numberType = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
int numberLabel = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LABEL);
int mimeType = cursor.getColumnIndex(ContactsContract.Contacts.Data.MIMETYPE);
int rawContactName = cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_NAME);
ContactComparator compId = new ContactComparator(ContactComparator.Type.ID);
ContactComparator compName = new ContactComparator(ContactComparator.Type.Name);
while (cursor.moveToNext())
{
int phId = cursor.getInt(id);
String phLookupKey = cursor.getString(lookupKey);
// String phPhotoUri = cursor.getString(photoUri);
int phPhotoId = cursor.getInt(photoId);
long phRawId = cursor.getLong(rawId);
String phNumber = cursor.getString(number);
int phNumberType = cursor.getInt(numberType);
String phNumberLabel = cursor.getString(numberLabel);
String phMimeType = cursor.getString(mimeType);
String phAccountType = cursor.getString(accountType);
String phRawContactName = cursor.getString(rawContactName);
PhoneContact contact = new PhoneContact(phId, phRawId, phLookupKey, phPhotoId > 0);
// funktioniert, weil Kontakte nach ID sortiert sind!
int contactIndex = Collections.binarySearch(contacts, contact, compId);
if (contactIndex < 0)
{
String phName = cursor.getString(name);
contact.setName(phName);
contacts.add(contact);
}
else
{
contact = contacts.get(contactIndex);
}
String accountName = BaseDef.makeAccountTypeReadable(phAccountType, phRawContactName);
contact.addAccountType(accountName);
// Liste der AccountTypen merken
if (!accountTypes.contains(accountName))
accountTypes.add(accountName);
if (phMimeType.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE))
{
String phoneLabel = (String) ContactsContract.CommonDataKinds.Phone.getTypeLabel(MainApp.get().getResources(), phNumberType, phNumberLabel);
contact.addNumber(phoneLabel, phNumber);
}
}
cursor.close();
Is this function prone to errors? What could I change to avoid the error mentioned above?
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.
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);
I need to fetch the all events of all contacts in my android application.
Can anyone help me on this?
what I need to place the Uri for the below..
Cursor events = getContentResolver().query(xxxx,null,ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, null, null);
Try this method, it should work. Do the Log.d(tag, "Output here"); to test your output, but it should work. It does here.
public void getEvent(String contactId)
{
final String[] projection = new String[] {
Event.CONTACT_ID,
Event.START_DATE,
//Event.TYPE,
Event.LABEL
};
final String filter = Data.MIMETYPE + " = ? AND " + Data.CONTACT_ID + " = ? ";
final String parameters[] = {Event.CONTENT_ITEM_TYPE, contactId};
Cursor cursor = context.getContentResolver().query(Data.CONTENT_URI,
projection,
filter,
parameters,
null);
if(cursor.moveToFirst())
{
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
{
final String contact_id = cursor.getString(cursor.getColumnIndex(Event.CONTACT_ID));
final String startDate = cursor.getString(cursor.getColumnIndex(Event.START_DATE));
//final String type = cursor.getString(cursor.getColumnIndex(Event.TYPE));
final String label = cursor.getString(cursor.getColumnIndex(Event.LABEL));
}
}
}