Deleting a particular SMS message works sometimes - android

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!

Related

Deleting all text/mms messages programmatically. but some are leftover

I found two answers on Stackoverflow on how to delete SMS messages programmatically. I'm running this on an app which is set to be the default messaging app.
I have tried these two codes
This one which is supposed to delete everything. It deleted most, but about 4-5 did not get deleted.
this.getApplicationContext().getContentResolver().delete(Uri.parse("content://sms/"), null, null);
and this one, which removed less then the code above
Uri inboxUri = Uri.parse("content://sms/inbox");
int count = 0;
Cursor c = context.getContentResolver().query(inboxUri , 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) {
}
}
Any idea why a few messages are not being deleted? Any other way to delete all the SMS/MMS messages on the phone?

Android content provider query not retrieving updated information

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?

Get contact phone number by ID - empty Cursor

So I'm having trouble getting the phone number of a contact using its id.
This is the code I'm using to retrieve the number:
public String getNumber(){
//gets numbers by id
if (hasPhoneNumber){
ContentResolver contentResolver=context.getContentResolver();
Cursor cursor=contentResolver.query(
ContactsContract.Contacts.CONTENT_URI,
null,
ContactsContract.Contacts._ID+" = "+id,
null,
null
); //TODO : resolve empty cursor error
//contact seems to have no data available?
if (cursor.moveToFirst()){
cursor.moveToNext();
String contactId=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor phones=contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID+" = "+contactId,
null,
null);
if (phones.moveToFirst()){
while (phones.moveToNext()) {
this.number=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
}
phones.close();
} else {
test("cursor error...");
}
cursor.close();
return number;
} else {
return null;
}
}
It works with a few contacts but most show the "cursor error..." Toast (test("cursor error...") )
It's always the
Cursor cursor
that has the error.
My guess is it's empty but I know I have those contacts phone numbers saved. How do I fix this? Are there other values I have to request?
Thanks in advance!
EDIT:
this is how I retrieve ID and Name:
contactCursor=getActivity().getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{
ContactsContract.Contacts._ID,//0 - Long
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY,//1 - String
ContactsContract.Contacts.HAS_PHONE_NUMBER,//2 - Integer
},
null,
null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" ASC");
EDIT 2:
I have everything in a github repository: https://github.com/nicolas-d-torres/Syncc
The first block of Code is inside app/src/main/java/gtsarandum/syncc/SynccContact
the second in app/src/main/java/gtsarandum/syncc/ContactFragment
I know this answer is a little late but hopefully it will help someone else with a similiar issue. Both of your cursor queries use the id as a string
ContactsContract.Contacts._ID+" = "+id,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID+" = "+contactId,
should be
ContactsContract.Contacts._ID + " = " + Uri.encode(id),
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ Uri.encode(contactId),

Android get contact id from thread id

I'm working on a simple sms app and I'm using the code below to get the thread id when loading my threads list but I can't figure out how to get the contact id using the thread id. I'm root and using root explorer I can see in the database there is a contacts table with the following columns
thread_id | htcthread_id | contact_id
So since I have the thread id I should be able to get the contact id but I also need to make sure this works on all devices. My app is not root by the way
code to get thread id
Uri uri = Uri.parse("content://mms-sms/conversations?simple=true");
Cursor c = context.getContentResolver().query(uri, null, null, null, "date desc");
if (c.getCount() > 0) {
while (c.moveToNext()){
//thread id is c.getString(c.getColumnIndexOrThrow("_id"))
}
}
c.close
My solution to recover all contacts:
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(Phone.CONTENT_URI, null, null, null, null);
int contactIdIdx = cursor.getColumnIndex(Phone._ID);
int nameIdx = cursor.getColumnIndex(Phone.DISPLAY_NAME);
int phoneNumberIdx = cursor.getColumnIndex(Phone.NUMBER);
int photoIdIdx = cursor.getColumnIndex(Phone.PHOTO_ID);
cursor.moveToFirst();
do {
String idContact = cursor.getString(contactIdIdx);
String name = cursor.getString(nameIdx);
String phoneNumber = cursor.getString(phoneNumberIdx);
//...
} while (cursor.moveToNext());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
You need this permission in your manifest :
<uses-permission android:name="android.permission.READ_CONTACTS" />
I hope I have helped you!

Deleting Android SMS programmatically

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.

Categories

Resources