date format in sms inbox - android

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

Related

I am getting previous call duration instead of last call duration

I tried the below code in that ,the call duration getting is not correct, the previous call duration is shown to the current phone call. I tried the code and searched over the stack overflow ,problem is not solved.
private int outgoingCallDuration(Context context) {
int sum = 0;
StringBuffer sb = new StringBuffer();
try {
//
Cursor managedCursor = context.getContentResolver().query(android.provider.CallLog.Calls.CONTENT_URI, null, null, null, null);
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
sb.append("Call Details :");
Log.e("total count", "" + managedCursor.getCount());
//managedCursor.moveToPosition(managedCursor.getCount() - 1);
int currentCount = 0, lastPosition = 0;
while (managedCursor.moveToNext()) {
currentCount++;
//managedCursor.moveToPosition(managedCursor.getCount() - 1);
String phNumber = managedCursor.getString(number);
String callType = managedCursor.getString(type);
String callDate = managedCursor.getString(date);
java.sql.Date callDayTime = new java.sql.Date(Long.valueOf(callDate));
String callDurations = managedCursor.getString(duration);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
// lastPosition = currentCount;
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
lastPosition = currentCount;
}
lastPosition--;
// managedCursor.moveToLast();
managedCursor.moveToPosition(lastPosition);
int requiredNumber = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int durations = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
String phNumber = managedCursor.getString(requiredNumber);
String dur = managedCursor.getString(durations);
// Long durat = Long.parseLong(dur);
int myNum = Integer.parseInt(dur);
managedCursor.close();
Log.e("last position number ", phNumber);
Log.e("last position duration ", dur);
return myNum;
} catch (SecurityException ex) {
Log.d("CallReceiver", "outgoingCallDuration: Permission to read call is not allowed by user!");
return 0;
}
}
Please help me how to solve this. How to get the last call duration in android.
You need to use limit clause in your content query to get the last call details. So your content query will become
Cursor cur = getContentResolver().query( CallLog.Calls.CONTENT_URI,null, null,null, android.provider.CallLog.Calls.DATE + " DESC limit 1;");
Try this code :
public double getLastOutgoingCallDuration(Context context) {
Cursor c = context.getContentResolver()
.query(CallLog.Calls.CONTENT_URI, null, null, null, null);
double callDuration = 0;
if (c != null) {
while (c.moveToNext()) {
int type = Integer.parseInt(c.getString(c.getColumnIndex(CallLog.Calls.TYPE)));
String duration = c.getString(c.getColumnIndex(CallLog.Calls.DURATION));
if (type == CallLog.Calls.OUTGOING_TYPE)
callDuration = Double.parseDouble(duration);
c.close();
}
}
return callDuration;
}

Android Call Log data between two dates and Total duration of calls from same number.

want to get the call log history by today, yesterday, last seven days and last 30days along with that i want to show the total duration of incoming and outgoing calls of that particular number.
suppose abc has 3 outgoing and 1 incoming calls. i should get the total duration of those calls.
just let me know if we can get duration and calls log by cursor GroupBy or ORDER BY clause rather than looping and adding duration. Just give me rough structure for better solution and can work effectively .
String[] whereValue=null;
Calendar calendar = Calendar.getInstance();
String currentDate = String.valueOf(calendar.getTimeInMillis());
switch (period) {
case DAY:
whereValue = new String[]{getTimeFrom(period),currentDate};
break;
case YESTERDAY:
whereValue = new String[]{getTimeFrom(period),currentDate};
break;
case WEEK:
whereValue = new String[]{getTimeFrom(period),currentDate};
break;
case MONTH:
whereValue = new String[]{getTimeFrom(period),currentDate};
break;
default:
Log.d(Utils.LOG_TAG, "Error:");
}
String strOrder = android.provider.CallLog.Calls.DATE + " DESC";
Uri callUri = Uri.parse("content://call_log/calls");
Cursor cur = context.getContentResolver().query(callUri, null, android.provider.CallLog.Calls.DATE+" BETWEEN ? AND ?", whereValue, strOrder);
String callNumber = cur.getString(cur
.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
String callName = cur
.getString(cur
.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME));
String callType = cur.getString(cur
.getColumnIndex(android.provider.CallLog.Calls.TYPE));
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
case CallLog.Calls.INCOMING_TYPE:
break;
}
String duration = cur.getString(cur
.getColumnIndex(android.provider.CallLog.Calls.DURATION));
the above code is even not working for getting call log between fromdate to till date. any help?
I have managed to get the call log between two dates. You can get call log of today, yesterday, last seven days, last 30days. as well duration of calls (calls from same number multiple times also)
you should pass selection as
android.provider.CallLog.Calls.DATE + " BETWEEN ? AND ?"
and
selectionArgs
whereValue = new String[]{String.valueOf(calendar1.getTimeInMillis()),String.valueOf(calendar.getTimeInMillis());};
Map<String, StatEntry> callLogMap1 = new HashMap<>();
callLogMap1.clear();
String strOrder1 = android.provider.CallLog.Calls.DATE + " DESC limit 500";
Uri callUri = Uri.parse("content://call_log/calls");
Cursor cur = getContentResolver().query(CallLog.Calls.CONTENT_URI, null, android.provider.CallLog.Calls.DATE + " BETWEEN ? AND ?", whereValue,
strOrder1);
if (cur != null) {
try {
while (cur.moveToNext()) {
String callNumber = cur.getString(cur.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
// String callDate = cur.getString(cur.getColumnIndex(android.provider.CallLog.Calls.DATE));
int duration = cur.getInt(cur.getColumnIndex(android.provider.CallLog.Calls.DURATION));
String name = cur.getString(cur.getColumnIndex(CallLog.Calls.CACHED_NAME));
StatEntry StatEntry1 = null;
int id = cur.getInt(cur.getColumnIndex(CallLog.Calls._ID));
int type = cur.getInt(cur.getColumnIndex(CallLog.Calls.TYPE));
if (callNumber != null & duration > 0 && (type == 1 || type == 2)) {
int n = callNumber.length();
String lastDigits;
String number = callNumber.replaceAll(Pattern.quote("+"), ""); //replacing the plus
//am just checking last 5digitis and saving to map so that we can get same //number duration
if (n >= 5) {
try {
lastDigits = String.valueOf(Long.parseLong(number) % 100000);
} catch (NumberFormatException e) {
e.printStackTrace();
lastDigits = callNumber;
}
} else {
lastDigits = callNumber;
}
if (callLogMap1.containsKey(lastDigits)) {
StatEntry1 = callLogMap1.get(callNumber);
StatEntry1.setTitle(callNumber);
StatEntry1.Duration += duration;
} else {
StatEntry1 = new StatEntry();
StatEntry1.setTitle(callNumber);
StatEntry1.Duration += duration;
}
StatEntry1.setTime((StatEntry1.Duration) / 60);
callLogMap1.put(callNumber, StatEntry1);
}
}
} catch (Exception e) {
e.printStackTrace(
);
} finally {
cur.close();
}
}
atlast passing hashmap data to arraylist.
ArrayList<StatEntry> callLogList1 = new ArrayList<>(callLogMap1.size());
if (callLogMap1.size() > 0) {
for (Map.Entry<String, StatEntry> entry : callLogMap1.entrySet()) {
callLogList1.add(entry.getValue());
}
}
hope this will be helpful for viewers.
I managed to get the call log between two dates and also you can get the duration of the calls.Try this method..
public class CallLogActivity extends Activity {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call_log);
textView = (TextView) findViewById(R.id.textCallBetween);
textView.setVisibility(View.GONE);
// listcallLog = (ListView) findViewById(R.id.calllogItems);
getCalldetails();
}
public void getCalldetails() {
StringBuffer stringBuffer = new StringBuffer();
String strOrder = android.provider.CallLog.Calls.DATE + " DESC";
Calendar calender = Calendar.getInstance();
calender.set(2016, calender.NOVEMBER, 18);
String fromDate = String.valueOf(calender.getTimeInMillis());
calender.set(2016, calender.NOVEMBER, 20);
String toDate = String.valueOf(calender.getTimeInMillis());
String[] whereValue = {fromDate,toDate};
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Cursor managedCursor = getContentResolver().query(CallLog.Calls.CONTENT_URI, null, android.provider.CallLog.Calls.DATE + " BETWEEN ? AND ?", whereValue, strOrder);
// Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null, android.provider.CallLog.Calls.DATE, new String[]{" BETWEEN ? AND ?"}, strOrder);
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
stringBuffer.append("Call Log :");
while (managedCursor.moveToNext())
{
String phoneNumber = managedCursor.getString(number);
String callType = managedCursor.getString(type);
String callDate = managedCursor.getString(date);
SimpleDateFormat formatter = new SimpleDateFormat(
"dd-MMM-yyyy HH:mm");
String dateString = formatter.format(new Date(Long
.parseLong(callDate)));
// Date callDayTime = new Date(Long.valueOf(callDate));
String callDuration = managedCursor.getString(duration);
String dir = null;
int dirCode = Integer.parseInt(callType);
switch (dirCode)
{
case CallLog.Calls.OUTGOING_TYPE :
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED CALL";
break;
}
stringBuffer.append("\nPhone Number:--- " + phoneNumber + "\nCall Type:--- "
+ dir + "\nCall Date:---"
+ dateString + "\nCall Duration:---" + callDuration);
stringBuffer.append("\n--------------------------");
}
textView.setText(stringBuffer);
textView.setVisibility(View.VISIBLE);
}
}

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

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.

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