I am reading unread sms from a particular number by the following code .
public void getUnreadMessage() {
Cursor smsInboxCursor1 = getContentResolver().query(
Uri.parse("content://sms/inbox"), new String[] {},
"read = 0 and address='" + pre_address + "'", null, null);
int indexBody = smsInboxCursor1.getColumnIndex("body");
int indexAddress = smsInboxCursor1.getColumnIndex("address");
if (indexBody < 0 || !smsInboxCursor1.moveToFirst())
return;
// arrayAdapter.clear();
do {
String str = "SMS From: " + smsInboxCursor1.getString(indexAddress)
+ "\n" + smsInboxCursor1.getString(indexBody) + " \n";
fromNumber = smsInboxCursor1.getString(indexAddress);
smsBody.add(smsInboxCursor1.getString(indexBody));
// arrayAdapter.add(str);
status.add(false);
} while (smsInboxCursor1.moveToNext());
}
Now I want to get the time of receiving sms from this particular number . How can I do that ?
There is a column named DATE that contains the date the message was received. You can get directly like the other fields you already retrieve:
int indexData = smsInboxCursor1.getColumnIndex("data");
...
long dateReceived = smsInboxCursor1.getLong(indexData);
Since it's a timestamp you need to convert in a human readable string. You can do it with this code:
private String getDate(long time) {
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(time);
String date = DateFormat.format("dd-MM-yyyy HH:mm:ss", cal).toString();
return date;
}
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 am trying to read SMS stored in sim card . That is why I have written the following function .
void read_sms()
{
Cursor cursor = getContentResolver().query(Uri.parse("content://sms/icc"), null, null, null, null);
int indexBody = cursor.getColumnIndex("body");
int indexAddress = cursor.getColumnIndex("address");
if (indexBody < 0 || !cursor.moveToFirst())
return;
String fromNumber,smsMessageId;
try{
do {
SMSItem smsItem = new SMSItem();
String sms = cursor.getString(indexBody);
String str = "SMS From: " + cursor.getString(indexAddress)
+ "\n" + sms + " \n";
fromNumber = cursor.getString(indexAddress);
// arrayAdapter.add(str);
smsItem.sms = sms;
smsItem.status = false;
long millis = cursor.getLong(cursor
.getColumnIndexOrThrow("date"));
Date date = new Date(millis);
Calendar c = Calendar.getInstance();
// set the calendar to start of today
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
// and get that as a Date
Date today = c.getTime();
String smsDate;
if (date.before(today)) {
smsDate = (String) DateFormat.format(" MMMM dd ", new Date(
millis));
} else {
smsDate = (String) DateFormat.format(" h:mm ",
new Date(millis));
}
smsItem.time = smsDate;
smsMessageId = cursor.getString(cursor.getColumnIndex("_id"));
smsItem.ID = smsMessageId;
// Toast.makeText(this, "The id is "+smsMessageId,
// Toast.LENGTH_LONG).show();
smsBody.add(smsItem);
Toast.makeText(this, " "+smsItem.sms, Toast.LENGTH_LONG).show();
} while (cursor.moveToNext());
}
catch(Exception e)
{
Toast.makeText(this, "Message: "+e.getMessage(), Toast.LENGTH_LONG).show();
}
cursor.close();
}
But I am getting null pointer exception . Why am I getting null pointer exception ? How can I solve this ?
I tried putting your code in a test app and also got NPE (Null Pointer Exception). The trace tells me that the following line has a problem and returning NPE.
Cursor cursor = getContentResolver().query(Uri.parse("content://sms/icc"), null, null, null, null);
When I changed replaced line with following, things started working fine.
Cursor cursor = managedQuery(Uri.parse("content://sms"), null, null, null, null);
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 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.
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);
}
}