So I've written a query to extract the WhatsApp contacts of a phone. My initial query goes like this:
Cursor c = con.getContentResolver().query(
ContactsContract.RawContacts.CONTENT_URI,
new String[]{ContactsContract.RawContacts.CONTACT_ID, ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY},
ContactsContract.RawContacts.ACCOUNT_TYPE + "= ?",
new String[]{"com.whatsapp"},
null
);
ArrayList<String> myWhatsappContacts = new ArrayList<String>();
int contactNameColumn = c.getColumnIndex(ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY);
while (c.moveToNext()) {
// You can also read RawContacts.CONTACT_ID to read the
// ContactsContract.Contacts table or any of the other related ones.
myWhatsappContacts.add(c.getString(contactNameColumn));
}
The purpose of this is to find out how many WhatsApp contacts the phone has at any one time. When I do:
Log.i("WhatsApp contacts found:", Integer.toString(myWhatsappContacts.size());
It should print out how many WhatsApp contacts there were into LogCat. And this works - up to a point.
Let's say for example that the number of WhatsApp contacts I have now is 101. The next phase of this little project is to delete away ALL contacts if there are more than 100 of them. In which case, we go:
if (myWhatsappContacts.size() > 100) {
//Delete all contacts code here
}
I've tested the delete contacts code, it works. I check the contacts directory of the phone via the contacts app, and it says 0. But now when I do the query again (refer to code above), it still shows 101! What's going on?
If it helps, my DeleteContacts method is as follows:
private void deleteContact(Context ctx, String phone, String name) {
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
Cursor cur = ctx.getContentResolver().query(contactUri, null, null, null, null);
try {
if (cur.moveToFirst()) {
do {
if (cur.getString(cur.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)).equalsIgnoreCase(name)) {
String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
ctx.getContentResolver().delete(uri, null, null);
return;
}
} while (cur.moveToNext());
}
} catch (Exception e) {
System.out.println(e.getStackTrace());
} finally {
cur.close();
}
return;
}
What am I doing wrong? Is my DeleteContacts code faulty? Or is the query itself faulty?
I'm looking for the count of sent sms messages in a particular thread (say, with id 15). I found this How do I get the count of SMS messages per contact into a textview? <-- but it doesn't solve my issue, as it counts both sent and received sms messages. Is it possible to count only sent messages? I think I could query "content://sms/sent" and walk through each SMS, but I wonder if there's a more efficient way.
Thanks
You can query Sms.Conversations with your thread ID, and a selection that restricts the TYPE column to MESSAGE_TYPE_SENT. Since you just want the count, we can do a SELECT COUNT() query, so there's no resources wasted building a Cursor with unused values. For example:
private int getThreadSentCount(String threadId) {
final Uri uri = Sms.Conversations.CONTENT_URI
.buildUpon()
.appendEncodedPath(threadId)
.build();
final String[] projection = {"COUNT(1)"};
final String selection = Sms.TYPE + "=" + Sms.MESSAGE_TYPE_SENT;
int count = -1;
Cursor cursor = null;
try {
cursor = getContentResolver().query(uri,
projection,
selection,
null,
null);
if (cursor != null && cursor.moveToFirst()) {
count = cursor.getInt(0);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (cursor != null) {
cursor.close();
}
}
return count;
}
The Sms class used above is in the android.provider.Telephony class.
import android.provider.Telephony.Sms;
For reference, Sms.Conversations.CONTENT_URI is equivalent to Uri.parse("content://sms/conversations"), Sms.TYPE is "type", and Sms.MESSAGE_TYPE_SENT is 2.
I have tried variations on deleting all or some messages from the SMS, including but not limited to thread id, id, where clause, etc.
Android manifest reflects read and write permissions.
I tried with variations on the SMS content, from inbox etc.
Nothing seems to delete the record.
Here is the last iteration:
Cursor c = getApplicationContext().getContentResolver().query(Uri.parse("content://sms/"), null, null, null,null);
try {
while (c.moveToNext()) {
int Id = c.getInt(0);
String pid = c.getString(0);
// String uri = "content://sms/conversations/" + threadId;
String strUriAll = "content://sms/" + pid;//SMS_ALL
Log.d("URI is ", strUriAll);
getApplicationContext().getContentResolver().delete(Uri.parse(strUriAll), null, null);
// getApplicationContext().getContentResolver().delete(Uri.parse(strUriAll), null, null);
}
}catch(Exception e){
Log.e(this.toString(),"Error deleting sms",e);
}finally {
c.close();
}
Android 4.4 Kitkat introduced changes in SMS handling where now only the default SMS app is allowed write access to the SMS database - all other apps silently fail when attempting to write.
I am trying to delete particular SMS from given position on my list view. This works fine but not always. It works sometimes.. Sometimes doesn't delete at all.
I am not sure why this is happening can somebody let me know how to fix this up:
Here is what I am trying:
Cursor cursor = getContentResolver().query(Uri.parse("content://sms/?simple=true"), null, null, null, null);
if ( cursor.getCount() > 0 )
cursor.moveToPosition(position);
try
{
String pid = cursor.getString(0); // Get id;
String uri = "content://sms/" + pid;
getContentResolver().delete(Uri.parse(uri),
null, null);
}
catch (Exception e)
{
}
cursor.close();
Thanks!
I want to delete some certain SMS automatically in my Android application. Therefore I have a method which does exactly what I want it to do. However, it only works if I deploy the application directly to my phone from Eclipse. Then it deletes incoming SMS. However, it does not work if the application is downloaded from the market. But there is also no error. Does anybody know how I can solve this or does this only work on rooted devices?
public void deleteSMS(Context context, String message, String number) {
try {
mLogger.logInfo("Deleting SMS from inbox");
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor c = context.getContentResolver().query(uriSms,
new String[] { "_id", "thread_id", "address",
"person", "date", "body" }, null, null, null);
if (c != null && c.moveToFirst()) {
do {
long id = c.getLong(0);
long threadId = c.getLong(1);
String address = c.getString(2);
String body = c.getString(5);
if (message.equals(body) && address.equals(number)) {
mLogger.logInfo("Deleting SMS with id: " + threadId);
context.getContentResolver().delete(
Uri.parse("content://sms/" + id), null, null);
}
} while (c.moveToNext());
}
} catch (Exception e) {
mLogger.logError("Could not delete SMS from inbox: " + e.getMessage());
}
}
Actually, the code in my post is 100% correct. The problem was that Android needs some time to store the SMS upon receiving it. So the solution is to just add a handler and delay the delete request for 1 or 2 seconds.
This actually solved the whole issue.
EDIT (thanks to Maksim Dmitriev):
Please consider that you can't delete SMS messages on devices with Android 4.4.
Also, the system now allows only the default app to write message data to the provider, although other apps can read at any time.
http://developer.android.com/about/versions/kitkat.html
No exception will be thrown if you try; nothing will be deleted. I have just tested it on two emulators.
How to send SMS messages programmatically
Please consider that you can't delete SMS messages on devices with Android 4.4.
Also, the system now allows only the default app to write message data
to the provider, although other apps can read at any time.
http://developer.android.com/about/versions/kitkat.html
No exception will be thrown if you try; nothing will be deleted. I have just tested it on two emulators.
How to send SMS messages programmatically
hey use this code to delete customize sms
1. By date
2. By number
3. By body
try {
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor c = context.getContentResolver().query(
uriSms,
new String[] { "_id", "thread_id", "address", "person",
"date", "body" }, "read=0", null, null);
if (c != null && c.moveToFirst()) {
do {
long id = c.getLong(0);
long threadId = c.getLong(1);
String address = c.getString(2);
String body = c.getString(5);
String date = c.getString(3);
Log.e("log>>>",
"0--->" + c.getString(0) + "1---->" + c.getString(1)
+ "2---->" + c.getString(2) + "3--->"
+ c.getString(3) + "4----->" + c.getString(4)
+ "5---->" + c.getString(5));
Log.e("log>>>", "date" + c.getString(0));
ContentValues values = new ContentValues();
values.put("read", true);
getContentResolver().update(Uri.parse("content://sms/"),
values, "_id=" + id, null);
if (message.equals(body) && address.equals(number)) {
// mLogger.logInfo("Deleting SMS with id: " + threadId);
context.getContentResolver().delete(
Uri.parse("content://sms/" + id), "date=?",
new String[] { c.getString(4) });
Log.e("log>>>", "Delete success.........");
}
} while (c.moveToNext());
}
} catch (Exception e) {
Log.e("log>>>", e.toString());
}
You can choose which app is the default SMS app in 4.4+ and if your app is set as the default it will be able to delete SMS as well.
to make app as default app see this.
Check if your app is default sms app before deleting.
Use the URI provided by telephony class instead of hardcoding.
public void deleteSMS(Context context,int position)
{
Uri deleteUri = Uri.parse(Telephony.Sms.CONTENT_URI);
int count = 0;
Cursor c = context.getContentResolver().query(deleteUri, new String[]{BaseColumns._ID}, null,
null, null); // only query _ID and not everything
try {
while (c.moveToNext()) {
// Delete the SMS
String pid = c.getString(Telephony.Sms._ID); // Get _id;
String uri = Telephony.Sms.CONTENT_URI.buildUpon().appendPath(pid)
count = context.getContentResolver().delete(uri,
null, null);
}
} catch (Exception e) {
}finally{
if(c!=null) c.close() // don't forget to close the cursor
}
}
it delete all(inbox,outbox,draft) the SMS.
private int deleteMessage(Context context, SmsMessage msg) {
Uri deleteUri = Uri.parse("content://sms");
int count = 0;
#SuppressLint("Recycle") Cursor c = context.getContentResolver().query(deleteUri, null, null, null, null);
while (c.moveToNext()) {
try {
// Delete the SMS
String pid = c.getString(0); // Get id;
String uri = "content://sms/" + pid;
count = context.getContentResolver().delete(Uri.parse(uri),
null, null);
} catch (Exception e) {
}
}
return count;
}
use this code.............
or
getContentResolver().delete(Uri.parse("content://sms/conversations/" + threadIdIn), null, null);
I was looking for a method to delete all SMS with one click. Thanks to this post I succeeded.
Here is my method if it interests someone :
private void deleteSMS(){
Uri myUri= Uri.parse("content://sms/");
Cursor cursor = getContext().getContentResolver().query(myUri, null,null,null,null);
while (cursor.moveToNext()) {
int thread_id = cursor.getInt(1);
getContext().getContentResolver().delete(Uri.parse("content://sms/conversations/" + thread_id),null,null);
}
cursor.close();
}
if you want get a message and your sms app your android device phone didn't send any notification use Binary (Data) SMS.