First of all, I am very much new to Android programming.
I have written a program to delete SMS. I have already tested this code in Jelly Bean and it was working fine. Even in simulator with Android Marshmallow is was working fine. Recently I updated my mobile to Marshmallow and now SMS are not getting deleted from the app. Even No error is throw. Below is the code. I search for solution and tried different ways, but still no solution.
public void delete(final String id, final String number, final long date) {
Uri uri = Uri.parse("content://sms/inbox");
ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(uri, null, "person is null and _id = ?", new String[] { "" + id }, null);
if (c != null && c.moveToFirst()) {
do {
String pid = c.getString(c.getColumnIndex("_id"));
String pnumber = c.getString(c.getColumnIndex("address"));
Log.d("MyAPP", "id: " + pid);
if (id.equals(pid) && number.equals(pnumber)) {
Log.d("MyAPP", "Deleting SMS with id: " + id);
try{
cr.delete(Uri.parse("content://sms/" + id), null, null);
Log.d("MyAPP", "Delete success.........");
} catch (Exception ex) {
Log.d("MyAPP", "Error deleting msg");
}
}
} while (c.moveToNext());
}
}
Here is the log.
04-01 22:49:04.783: (1620): id: 39
04-01 22:49:04.783: (1620): Deleting SMS with id: 39
04-01 22:49:04.785: (1620): Delete success.........
Related
I'm trying to mark a message as read on a Samsung Galaxy S6 and it is not working. I have following tutorials online. My code is below:
Uri uri = Uri.parse("content://sms/inbox");
Cursor cursor = context.getContentResolver().query(uri, null, "_id=" + id, null, null);
try {
if (cursor.getCount() != 0) {
ContentValues values = new ContentValues();
values.put("read", true);
context.getContentResolver().update(uri, values, "_id=?", new String[] { id });
}
} catch (Exception e) {
Log.e("Mark Read", "Error in Read: " + e.toString());
} finally {
cursor.close();
}
Is there something i'm doing wrong? I pass in a id to this method and the message is always marked as unread. How is it that other SMS applications can mark as read and I cannot?
Turns out you cannot mark SMS messages as read if you are NOT the default SMS client. Lame!
I would like to get all messages from one contact. I have the contact ID _id, so I've already do something like this :
private void displayMessages() {
ContentResolver cr = this.getContentResolver();
try {
Cursor cursor = cr.query(Uri.parse("content://mms-sms/conversations"), new String[]{"*"}, this.contID + "= _id" , null, null); //contID is the unique ID for one contact in our android.
while (cursor.moveToNext()) {
System.out.println("Number: " + cursor.getString(cursor.getColumnIndexOrThrow("address")));
System.out.println("Body : " + cursor.getString(cursor.getColumnIndexOrThrow("body")));
}
cursor.close();
}
catch (Exception e) {
System.out.print("ERROR");
}
I've asked something like
SELECT * FROM content://mms-sms/conversations WHERE _id = contID
As you can see, in my query, I ask system for messages from one contact (user id that I know) But I can just display the last message body. So I think it exists others query to get all messages from one user ?
Any ideas ???
I doubt that _id in this case is the id of the contact you are sending sms/mms to but rather the thread's id. The column you probably want to use for your query clause is RECIPIENT_IDS. For debugging purpose try without the where clause and dump the cursor to analyze the results
Cursor cursor = cr.query(Uri.parse("content://mms-sms/conversations"), new String[]{"*"}, null , null, null);
DatabaseUtils.dumpCursor(cursor);
Sorry for answer too late, but I've found a solution.
Here is my code :
private void displayMessages() {
ContentResolver cr = this.getContentResolver();
boolean isMe;
try {
Cursor cursor = cr.query(Uri.parse("content://sms"), null, this.cont.getThread_ID() + " = thread_id" , null, "date ASC");
while (cursor.moveToNext()) {
//if it's a received message :
if ((cursor.getString(cursor.getColumnIndexOrThrow("person")) != null)) {
isMe = false;
}
else {
//it's a message sent by me.
isMe = true;
}
date = cursor.getString(cursor.getColumnIndexOrThrow("date"));
System.out.println("Number: " + cursor.getString(cursor.getColumnIndexOrThrow("address")));
System.out.println("Body : " + cursor.getString(cursor.getColumnIndexOrThrow("body") + "\n");
}
cursor.close();
}
Thanks to "conent://sms" table, I can get all sms !
So I've used thread_id to display all messages, and thanks to the person column, I can know if the message was sent by me or my contact.
looking at my google analytics page lately, I have seen that sometimes an exception is raised and I have no clue to resolve it as I have not been able to reproduce it. The idea of the code is to check if a custom contacts group exists and if not, create it. The code is the following:
public static long ensureSampleGroupExists(Context context, Account account) {
Log.v(TAG, "ensureSampleGroupExists");
final ContentResolver resolver = context.getContentResolver();
// Lookup the sample group
long groupId = 0;
final Cursor cursor = resolver.query(Groups.CONTENT_URI,
new String[] { Groups._ID },
Groups.ACCOUNT_NAME + "=? AND " + Groups.ACCOUNT_TYPE
+ "=? AND " + Groups.TITLE + "=?", new String[] {
account.name, account.type, SAMPLE_GROUP_NAME }, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
groupId = cursor.getLong(0);
}
} finally {
cursor.close();
}
}
if (groupId == 0) {
// Sample group doesn't exist yet, so create it
final ContentValues contentValues = new ContentValues();
contentValues.put(Groups.ACCOUNT_NAME, account.name);
contentValues.put(Groups.ACCOUNT_TYPE, account.type);
contentValues.put(Groups.TITLE, SAMPLE_GROUP_NAME);
contentValues.put(Groups.GROUP_IS_READ_ONLY, true);
final Uri newGroupUri = resolver.insert(Groups.CONTENT_URI,
contentValues); //<-- NULLPOINTER EXCEPTION IN SOME DEVICES (or at least 1 :P)
groupId = ContentUris.parseId(newGroupUri);
}
return groupId;
}
I can see in the google analytics webpage the following exception --
NullPointerException (#ContactManager:ensureSampleGroupExists:95) {SyncAdapterThread-1}
Not sure if the problem is the ContentResolver but when checked it was not null (neither was null the context) so i am a little bit confused...
Unfortunately there is no bug report so I have no stack trace:(, does somebody have any clue about what could be happening? Any help would be highly appreciated
Thank you
EDIT
I managed to get the full stacktrace thanks to GA 4, check it out
java.lang.NullPointerException at
android.os.Parcel.readException(Parcel.java:1478)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:185)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:137)
at android.content.ContentProviderProxy.insert(ContentProviderNative.java:468)
at android.content.ContentResolver.insert(ContentResolver.java:1190)
at com.smm.epctrackerapp.sqlite.ContactManager.ensureSampleGroupExists(ContactManager.java:96)
at com.smm.epctrackerapp.adapter.ContactSyncAdapter.onPerformSync(ContactSyncAdapter.java:72)
at android.content.AbstractThreadedSyncAdapter$SyncThread.run(AbstractThreadedSyncAdapter.java:259)
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.
I'm still very new to android app development, and I have hit a problem I hope u can help me with...
I am trying to retrieve any "Notes" stored against a contact within my phone. I want to check if a contact (current caller) has any notes associated to them, and then either display the contents or do some action depending on the content of them etc...
I have tried the code below as a test to see if the data is retrieved anywhere within my cursor, but although it retrieves some data, I can't see the content of a note - so I guess I'm in the wrong place!
Where I have declared contentID, this is a result of doing a lookup with the code below, and using the id that is recieved.
Uri lookupUri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(inCommingNumber));
String[] mPhoneNumberProjection = { Phone._ID, Phone.NUMBER, Phone.DISPLAY_NAME};
Cursor cur = getContentResolver().query(lookupUri , mPhoneNumberProjection, null, null, null);
private boolean hasNote(String contactID){
Boolean noteFound = false;
Cursor noteCur = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, null, null, null);
if(noteCur.moveToFirst()) {
int numCols = noteCur.getColumnCount();
if(numCols > 0){
for(int x = 0; x < numCols; x++){
Log.d(APP_TAG, " column " + x + " contains: " + noteCur.getString(x));
}
}
noteFound = true;
} else{
Log.d(APP_TAG, "No Note retrieved");
}
noteCur.close();
return noteFound;
}
Apologies, I cant seem to get the code to display properly in this post!!
Any help would be great
I have tried various things, but can't seem to be able to get this data. I have created the note by simply adding it through the normal contact manager. I'm using Android 2.2.
The following code would display the first note for all contacts on your phone:
Cursor contactsCursor = null;
try {
contactsCursor = getContentResolver().query(RawContacts.CONTENT_URI,
new String [] { RawContacts._ID },
null, null, null);
if (contactsCursor != null && contactsCursor.moveToFirst()) {
do {
String rawContactId = contactsCursor.getString(0);
Cursor noteCursor = null;
try {
noteCursor = getContentResolver().query(Data.CONTENT_URI,
new String[] {Data._ID, Note.NOTE},
Data.RAW_CONTACT_ID + "=?" + " AND "
+ Data.MIMETYPE + "='" + Note.CONTENT_ITEM_TYPE + "'",
new String[] {rawContactId}, null);
if (noteCursor != null && noteCursor.moveToFirst()) {
String note = noteCursor.getString(noteCursor.getColumnIndex(Note.NOTE));
Log.d(APP_TAG, "Note: " + note);
}
} finally {
if (noteCursor != null) {
noteCursor.close();
}
}
} while (contactsCursor.moveToNext());
}
} finally {
if (contactsCursor != null) {
contactsCursor.close();
}
}
If you are storing some sort of structured data on the note to take actions on using the free form note field may not be the best approach. With the new contacts contract model you are able to attach your own data fields (in ContactsContract.Data) to a contact just give them your own unique mimetype.