getContentResolver().query with CallLog - java

I'm working on an Android app. I need to get call log to get info about outcoming calls. I´m using this one (from some topic here):
private void getCallDetails() {
StringBuffer sb = new StringBuffer();
Cursor managedCursor = managedQuery( 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 :");
while ( managedCursor.moveToNext() ) {
String phNumber = managedCursor.getString( number );
String callType = managedCursor.getString( type );
String callDate = managedCursor.getString( date );
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 = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
sb.append( "\nPhone Number:--- "+phNumber +" \nCall Type:--- "+dir+" \nCall Date:--- "+callDayTime+" \nCall duration in sec :--- "+callDuration );
sb.append("\n----------------------------------");
}
managedCursor.close();
call.setText(sb);
}
I can use this newer code too:
Cursor c = getContentResolver().query(CallLog.Calls.CONTENT_URI,null, null,null, null);
but in both examples my app crashes on phone even on emulator. I tried to fix that only think I find out is that this query line is the problem but only with CallLog.
When I use similar code with sms for example everythink is working fine.
public StringBuffer getOutgoingSMSContent() {
ContentResolver contentResolver = getContentResolver();
Uri uri = Uri.parse("content://sms/sent/");
StringBuffer messagedata = new StringBuffer();
int count = 0;
Cursor cursor = contentResolver.query(uri, null, null, null, null);
if (cursor.getCount() != 0) {
if (cursor.moveToFirst()) {
do {
messagedata.append("Outgoing message count: " + (count + 1)
+ "\n");
for (int m = 0; m < cursor.getColumnCount(); m++) {
if (cursor.getColumnName(m).equalsIgnoreCase("address")
|| cursor.getColumnName(m).equalsIgnoreCase(
"date")
|| cursor.getColumnName(m).equalsIgnoreCase(
"body")
|| cursor.getColumnName(m).equalsIgnoreCase(
"type")) {
messagedata.append(cursor.getColumnName(m) + " : "
+ cursor.getString(m));
messagedata.append("\n");
}
}
messagedata.append("\n");
count++;
} while (cursor.moveToNext());
}
}
cursor.close();
cursor = null;
return messagedata;
}
Any idea?

Related

Tracking phone call time in real time

I have a recording call app in which i would like to track the call duration in realtime , i have looked up some codes online but none of them does what i want , i'm here seeking help from those who are expert in this , any way to do that please , Thank you .
Basically when the call is answered , track call timing 0 1 2 3 and so on .
Tried this code but only gets the final duration
private void getCallDetails() {
StringBuffer sb = new StringBuffer();
Uri contacts = CallLog.Calls.CONTENT_URI;
Cursor managedCursor = this.getContentResolver().query(contacts, 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 :");
while (managedCursor.moveToNext()) {
HashMap rowDataCall = new HashMap<String, String>();
String phNumber = managedCursor.getString(number);
String callType = managedCursor.getString(type);
String callDate = managedCursor.getString(date);
String callDayTime = new Date(Long.valueOf(callDate)).toString();
// long timestamp = convertDateToTimestamp(callDayTime);
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 = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
Log.d("TAG","Call Duration" + callDuration);
}
managedCursor.close();
System.out.println(sb);
}

How to get the Call Log data between two dates and Total number of incoming an outgoing calls between the dates

I 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.
I tried with various type but none of them working. What should i do to get the output ?.I have no idea how to use the query to get the call log from specific date. Help me Thanks
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.getTime());
calender.set(2016, Calendar.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);
}`
}
The below code is the solution for getting call log data between two dates.
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);
}
}
go step by step . first get all call log history this way.
Uri allCalls = Uri.parse("content://call_log/calls");
Cursor c = managedQuery(allCalls, null, null, null, null);
String num= c.getString(c.getColumnIndex(CallLog.Calls.NUMBER));// for number
String name= c.getString(c.getColumnIndex(CallLog.Calls.CACHED_NAME));// for name
String duration = c.getString(c.getColumnIndex(CallLog.Calls.DURATION));// for duration
int type = Integer.parseInt(c.getString(c.getColumnIndex(CallLog.Calls.TYPE)));// for call type, Incoming or out going.

how to determine whether last call was outgoing or incoming in android

I am using android call logs in my app and I would like to determine whether the last call was an incoming or out going call. This is what I have tried so far however int type gives me an error android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 284
Cursor managedCursor = context.getContentResolver().query( CallLog.Calls.CONTENT_URI,null, null,null, android.provider.CallLog.Calls.DATE + " DESC");
int number = managedCursor.getColumnIndex( CallLog.Calls.NUMBER );
int duration1 = managedCursor.getColumnIndex( CallLog.Calls.DURATION);
int type = Integer.parseInt(managedCursor.getString(managedCursor.getColumnIndex(CallLog.Calls.TYPE)));
Log.v("DialBroadcast Receiver", "Number is: " + type);
if( managedCursor.moveToFirst() == true ) {
String phNumber = managedCursor.getString( number );
callDuration = managedCursor.getString( duration1 );
String dir = null;
sb.append( "\nPhone Number:--- "+phNumber +" \nCall duration in sec :--- "+callDuration );
sb.append("\n----------------------------------");
Log.i("*****Call Summary******","Call Duration is:-------"+sb);
Log.v("DialBroadcast Receiver", "Number is: " + callDuration);
}
Try this
public String getLastDialledNumber() {
String[] projection = {Calls.NUMBER};
Cursor cursor = mContext.getContentResolver().query(Calls.CONTENT_URI, projection,
Calls.TYPE + "=" + Calls.OUTGOING_TYPE, null, Calls.DEFAULT_SORT_ORDER +
" LIMIT 1");
if (cursor == null) return null;
if (cursor.getCount() < 1) {
cursor.close();
return null;
}
cursor.moveToNext();
int column = cursor.getColumnIndexOrThrow(Calls.NUMBER);
String number = cursor.getString(column);
cursor.close();
return number;
}
For details
How do I access call log for android?
you are get
int type = Integer.parseInt(managedCursor.getString(managedCursor.getColumnIndex(CallLog.Calls.TYPE)));
before chek if( managedCursor.moveToFirst()){}
that's why you get exeption.
put this line inside of if or try this method
private static String getCallDetails(Context context) {
StringBuffer stringBuffer = new StringBuffer();
Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI,
null, null, null, CallLog.Calls.DATE + " DESC");
int number = cursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = cursor.getColumnIndex(CallLog.Calls.TYPE);
int date = cursor.getColumnIndex(CallLog.Calls.DATE);
int duration = cursor.getColumnIndex(CallLog.Calls.DURATION);
while (cursor.moveToNext()) {
String phNumber = cursor.getString(number);
String callType = cursor.getString(type);
String callDate = cursor.getString(date);
Date callDayTime = new Date(Long.valueOf(callDate));
String callDuration = cursor.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 = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
stringBuffer.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- "
+ dir + " \nCall Date:--- " + callDayTime
+ " \nCall duration in sec :--- " + callDuration);
stringBuffer.append("\n----------------------------------");
}
cursor.close();
return stringBuffer.toString();
}

Android search music

I search about read song in android and I see a code from you:
private static ArrayList<SongModel> LoadSongsFromCard() {
ArrayList<SongModel> songs = new ArrayList<SongModel>();
// Filter only mp3s, only those marked by the MediaStore to be music and longer than 1 minute
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0"
+ " AND " + MediaStore.Audio.Media.MIME_TYPE + "= 'audio/mpeg'"
+ " AND " + MediaStore.Audio.Media.DURATION + " > 60000";
final String[] projection = new String[] {
MediaStore.Audio.Media._ID, //0
MediaStore.Audio.Media.TITLE, //1
MediaStore.Audio.Media.ARTIST, //2
MediaStore.Audio.Media.DATA, //3
MediaStore.Audio.Media.DISPLAY_NAME
};
final String sortOrder = MediaStore.Audio.AudioColumns.TITLE
+ " COLLATE LOCALIZED ASC";
Cursor cursor = null;
try {
// the uri of the table that we want to query
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; //getContentUriForPath("");
// query the db
cursor = _context.getContentResolver().query(uri,
projection, selection, null, sortOrder);
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
//if (cursor.getString(3).contains("AwesomePlaylists")) {
SongModel GSC = new SongModel();
GSC.ID = cursor.getLong(0);
GSC.songTitle = cursor.getString(1);
GSC.songArtist = cursor.getString(2);
GSC.path = cursor.getString(3);
// This code assumes genre is stored in the first letter of the song file name
String genreCodeString = cursor.getString(4).substring(0, 1);
if (!genreCodeString.isEmpty()) {
try {
GSC.genre = Short.parseShort(genreCodeString);
} catch (NumberFormatException ex) {
Random r = new Random();
GSC.genre = (short) r.nextInt(4);
} finally {
songs.add(GSC);
}
}
//}
cursor.moveToNext();
}
}
} catch (Exception ex) {
} finally {
if (cursor != null) {
cursor.close();
}
}
return songs;
}
I'm really learning to program for Android, and modify your code for what I needed , but I have trouble understanding when you assign cursor
cursor = _context.getContentResolver () query ( uri , projection , selection , null, sortOrder ) . ;
Part of _context not understand you kindly explain it please.
If your class extends activity you can use this for _context. If not, you need to pass the context from your activity. The first case mentioned would look like this:
// query the db
cursor = this.getContentResolver().query(uri, projection, selection, null, sortOrder);
__
What is Context in Android?

Getting order by given order android SQlite Android

I have an book mark option in my application, here to sort in SQLITE by "order by" using selected set of column values (ID) like: order by (ID=1,5,4,3) so I would get record 1, 5, 4, 3 in that order out,
But it show id=1,2,3,4,5 in listview please any one help me.
databasehelper activity
public Cursor getBookMarks() {
try{
SQLiteDatabase db =myDataBase;// getReadableDatabase();
SQLiteQueryBuilder qb1 = new SQLiteQueryBuilder();
String [] sqlSelect1 = {"0 _id", KEY_NAME,KEY_PH_NO,KEY_ID};
String sqlTables1 = TABLE_BOOKMARK;
String strQuery1=KEY_PH_NO+"='1'";
strOrder1=KEY_ID + " DESC";
qb1.setTables(sqlTables1);
String strvalues="";
Cursor curs = qb1.query(db, sqlSelect1, strQuery1, null,null, null, strOrder1);
if(curs!=null)
{
curs.moveToFirst();
if(curs.getCount()>=1)
{
do
{
strvalues+=""+curs.getString(curs.getColumnIndex(KEY_NAME))+",";
}
while (curs.moveToNext());
if(strvalues.length()>=1)
{
strvalues+="-1";
String [] sqlSelect = {"0 _id", "TB","Version","Book","Chapter","NKJ"};
String sqlTables = "hindibible";
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(sqlTables);
String strOrderbook="Book" + " desc";
StringBuilder strQuery = new StringBuilder();
strQuery.append("ID IN (" +strvalues + ")");
StringBuilder strOrderBy = new StringBuilder();
strOrderBy.append(" CASE ID ");
String [] arrIDs = strvalues.split(",");
for(int i=0;i<arrIDs.length;i++)
{
strOrderBy.append(" WHEN " + arrIDs[i] + " THEN " + arrIDs[i]);
}
strOrderBy.append(" END");
Cursor bible = qb.query(db, sqlSelect, strQuery.toString(), null,null, null, strOrderBy.toString());
bible.moveToFirst();
return bible;
}
}
else
{
}
}
else
{
}
}catch (Exception e) {
Log.d("setBookMark",e.toString());
}
return null;
}
I am trying this
if(curs!=null)
{
List<Cursor> listCursor = new ArrayList<Cursor>();
curs.moveToFirst();
if(curs.getCount()>=1)
{
do
{
String strID = curs.getString(curs.getColumnIndex(KEY_NAME));
String [] sqlSelect = {"0 _id", "TB", "Version", "Book", "Chapter", "NKJ"};
String sqlTables = "hindibible";
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(sqlTables);
StringBuilder strQuery = new StringBuilder();
strQuery.append("ID = "+strID);
Cursor bible = qb.query(db, sqlSelect, strQuery.toString(), null,null, null,null);
listCursor.add(bible);
}while (curs.moveToNext());
return listCursor;
}

Categories