Reading browsing date and time in Android - 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.

Related

How to get the time of receiving of an sms

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;
}

Capturing browsing history from android browsers for the last few minutes

I would like to capture browsing history of all the browsers in an android phone for the last few (5 or 10) minutes. The code i am using is
Calendar ci = Calendar.getInstance();
String enddate = "" + 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);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ci = Calendar.getInstance();
ci.add(Calendar.MINUTE, -5);
String startdate = "" + 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);
long startdates = 0;
long enddates = 0;
try {
Date endDate = (Date) new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.parse(enddate);
Date startDate = (Date) new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.parse(startdate);
System.out.println("End date=" + endDate.getTime());
startdates = startDate.getTime();
enddates = endDate.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
String[] proj = new String[] {
Browser.BookmarkColumns.TITLE, Browser.BookmarkColumns.URL,
Browser.BookmarkColumns.DATE
};
Uri uriCustom = Uri
.parse("content://com.android.chrome.browser/bookmarks");
// 0 = history, 1 = bookmark
String sel = Browser.BookmarkColumns.BOOKMARK + " = 0" + " AND "
+ Browser.BookmarkColumns.DATE + " BETWEEN ? AND ?";
Cursor mCur = getContentResolver().query(uriCustom, proj, sel,
new String[] {
"" + startdates, "" + enddates
}, null);
mCur.moveToFirst();
JSONObject obj;
JSONArray jarray = new JSONArray();
String title = "";
String burl = "";
String date_time = "";
if (mCur.moveToFirst() && mCur.getCount() > 0) {
while (mCur.isAfterLast() == false) {
title = mCur.getString(mCur
.getColumnIndex(Browser.BookmarkColumns.TITLE));
burl = mCur.getString(mCur
.getColumnIndex(Browser.BookmarkColumns.URL));
date_time = mCur.getString(mCur
.getColumnIndex(Browser.BookmarkColumns.DATE));
try {
obj = new JSONObject();
obj.put("title", title);
obj.put("url", burl);
obj.put("date", date_time);
jarray.put(obj);
} catch (Exception e)
{
e.printStackTrace();
}
mCur.moveToNext();
System.out.println(title);
}
}
I can get the whole browsing history from chrome browser if i change
String sel = Browser.BookmarkColumns.BOOKMARK + " = 0" +" AND " +Browser.BookmarkColumns.DATE+ " BETWEEN ? AND ?"; // 0 = history, 1 = bookmark
to
String sel = Browser.BookmarkColumns.BOOKMARK; // 0 = history, 1 = bookmark
but i need the browsing history for the last few minutes to update database. I am new to android developing. Any help would be greatly appreciated. Thanks in advance..
You CANNOT get the history from ALL the browsers, you just can get the history for the default browser(which came with the phone).
The other browser use private scope to keep this info, there is no API.
The params to fill the "?" on sel need to be a timestamp (long), not a yyyy/mm/dd format.
Just do:
final Calendar ci = Calendar.getInstance();
final long endDate = ci.getTimeInMillis();
ci.add(Calendar.MINUTE, -5);
final long startDate = ci.getTimeInMillis();
final String[] paramsSel = new String[] { String.valueOf(startDate), String.valueOf(endDate) };
Note: use String.valueOf to cast any class to a String, don't use (""+) could be wrong, for example when cast a float, the separator will be not be localiced (, instead . or viceversa).
Hope it's works.

Android CalendarProvider query provides strange start and end times

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.

How to read events for a particular date from native calendar

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();
}

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