How can I delete ALL messages in the SMS inbox in Android? - android

I wanna delete ALL the messages in my Messaging with just one click on the button. But I already tried the coding below, it is not working... Can someone just help me to achieve this? Thanks...
public class DeleteSMSActivity extends Activity implements OnClickListener{
/** Called when the activity is first created. */
Button press;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
press = (Button)findViewById(R.id.button1);
press.setOnClickListener(this);
}
public void onClick(View view){
ContentResolver cr = getContentResolver();
Uri inboxUri = Uri.parse("content://sms/inbox");
Cursor c = cr.query(inboxUri , null, null, null, null);
while (c.moveToNext()) {
// Delete the SMS
String pid = c.getString(0); // Get id;
String uri = "content://sms/" + pid;
cr.delete(Uri.parse(uri), null, null);
}
}
}
What should I add in Manifest? Having force close when testing with my Galaxy Tab 2

Try deleting with _id :
Cursor c = getApplicationContext().getContentResolver().query(Uri.parse("content://sms/"), null, null, null,null);
try {
while (c.moveToNext()) {
int id = c.getInt(0);
getApplicationContext().getContentResolver().delete(Uri.parse("content://sms/" + id), null, null);
}
}catch(Exception e){
Log.e(this.toString(),"Error deleting sms",e);
}finally {
c.close();
}

The delete uri is "content://sms/" + id;
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) {
}
}
return count;
you can Also Refere HERE & HERE for More Detail Information About this topic.
Hope it Will Help you.

for Deleting SMS from inbox you need uses permission declared in your manifest
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.WRITE_SMS"/>
now you will be able to delete your inbox sms and now you wont get the force close your emulator

Today I found the way to delete all messages without loop, just by query.
mContext.getContentResolver().delete(Uri.parse("content://sms/"), null, null);
Follow this link for more detail
http://www.wisdomitsol.com/blog/android/sms/programmatically-delete-all-messages-in-android

Related

My phone number in mms address field of android conversation

I develop simple sms/mms client. With sms everything work good, but with mms I have problem related to address field in conversation.
I have next method to load conversations. There are last sms and mms.
public static List<Conversation> getConversations(Context c) {
List<Conversation> conversations = new ArrayList<>();
Conversation conversation;
Uri uri = Uri.parse("content://mms-sms/conversations/");
Cursor cursor = c.getContentResolver().query(uri, null, null, null, "normalized_date DESC");
if (cursor.moveToFirst()) {
for (int i = 0; i < cursor.getCount(); i++) {
conversation = new Conversation();
conversation.setId(cursor.getString(cursor.getColumnIndexOrThrow("_id")));
conversation.setThreadID(cursor.getString(cursor.getColumnIndexOrThrow("thread_id")));
conversation.setDate(new Date(Long.valueOf(cursor.getString(cursor.getColumnIndexOrThrow("date")))));
conversation.setReadType(ReadType.values()[Integer.parseInt(cursor.getString(cursor.getColumnIndexOrThrow("read")))]);
String type = cursor.getString(cursor.getColumnIndexOrThrow("type"));
if (isSMS(type)) {
conversation.setBody(cursor.getString(cursor.getColumnIndexOrThrow("body")));
conversation.setNumber(cursor.getString(cursor.getColumnIndexOrThrow("address")));
conversation.setMessageFromType(MessageFromType.values()[Integer.parseInt(type) - 1]);
} else {
Map<String, String> mmsContent = getMMSByID(c, conversation.getId());
conversation.setBody(mmsContent.get("body"));
conversation.setNumber(mmsContent.get("address"));
}
conversations.add(conversation);
cursor.moveToNext();
}
}
cursor.close();
return conversations;
}
The problem is that when I sent mms, my number was put to address field of conversation. With sms everything is okay. So after that I don't know who is my opponent in chat.
Also I load mms number in the next way
private String getNumber(Context c, String mmsdid) {
String add = "";
final String[] projection = new String[]{"address", "contact_id"};
Uri.Builder builder = Uri.parse("content://mms").buildUpon();
builder.appendPath(String.valueOf(mmsid)).appendPath("addr");
Cursor cursor = c.getContentResolver().query(
builder.build(),
projection,
null,
null, null);
if (cursor.moveToFirst()) {
add = cursor.getString(cursor.getColumnIndex("address"));
}
return add;
}
Maybe someone have the same problem? Or have any suggestions how to solve it?
The answer was pretty easy, hope it may help someone. Everything is okay except one part. In selection parameter I should add
"from=151"
or
"from="+PduHeaders.TO
So code will look like this:
private static String getNumber(Context c, String id) {
String add = "";
final String[] projection = new String[]{"address"};
Uri.Builder builder = Uri.parse("content://mms").buildUpon();
builder.appendPath(String.valueOf(id)).appendPath("addr");
Cursor cursor = c.getContentResolver().query(
builder.build(),
projection,
"type="+PduHeaders.TO,
null, null);
if (cursor.moveToFirst()) {
add = cursor.getString(cursor.getColumnIndex("address"));
}
cursor.close();
return add;
}

How to retrieve a record from sqlite

Hi i'm new to android programming and i have created a sample app which allows the user to get data from the database. however its not displaying the data, it doesn't have any error message its just not displaying it. database is confirmed that there is data. please check my code maybe i forgot something here. thanks
public void onClick(View arg){
name = txtNameS.getText().toString();
if(arg.getId()==R.id.btnfortune){
searchRecord(count);
lblmessageS1.setText(name); // this is just for me to check if it will be displayed and it is.
lblmessageS2.setText(message);
}
}
public void searchRecord(int count) throws SQLException {
Cursor rsCursor;
String [] rsFields = {"mesNum","Message"};
rsCursor = dbM.dbase.query("MessageFile", rsFields, "mesNum = " + count, null, null, null, null, null);
rsCursor.moveToFirst();
if (rsCursor.isAfterLast()==false){
message = rsCursor.getString(1);
}
rsCursor.close();
}
by the way count is initialized as 1. and there are 10 records in the database. and there are 2 columns in the database the mesNum and Message, what i want is to display only the message column.
// SQLiteDatabase sqldb
Cursor rsCursor= sqldb.rawQuery("your query", null);
if (rsCursor!= null) {
if (rsCursor.moveToFirst()) {
do {
// do here for get data message = rsCursor.getString(1);
}while (cursor.moveToNext());
}
cursor.close();
}
add only one column name in your array
String [] rsFields = {"Message"};
cursor = dbM.dbase.query(true,"MessageFile", rsFields, "yourcolumn= "+count, null, null, null, null, null);
while( cursor != null && cursor.moveToNext() )
{
cursor.getString(0);
}
cursor.close();

Search sms Inbox

How can I search the sms inbox and show latest message from a special number. For example search for "999999999" and show last message received from this number. Is any way to do this?
I have use this code to return the count of messages my inbox
TextView view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
view = (TextView) findViewById(R.id.textView1);
final Uri SMS_INBOX = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(SMS_INBOX, null, null, null, null);
int unreadMessagesCount = c.getCount();
c.deactivate();
view.setText(String.valueOf(unreadMessagesCount));
If you only want the last message sent by a specific number use this:
final Uri SMS_INBOX = Uri.parse("content://sms/inbox");
Cursor cursor = getContentResolver().query(SMS_INBOX, null, "address = ?",
new String[] {"9999999999"}, "date desc limit 1");
if(cursor.moveToFirst()) {
// Do something
Log.v("Example", cursor.getString(cursor.getColumnIndex("body")));
}
cursor.close();
The second answer to How many database columns associated with a SMS in android? is a great reference for different columns in an SMS.
try as:
final Uri SMS_INBOX = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(SMS_INBOX,null,null, null,"DATE desc");
if(c.moveToFirst()){
for(int i=0;i<c.getCount();i++){
String body= c.getString(c.getColumnIndexOrThrow("body")).toString();
String number=c.getString(c.getColumnIndexOrThrow("address")).toString();
if(number=="999999999")
{
//get message body here
break;
}
else
c.moveToNext();
}
}
c.close();

Media Query Cursor keeps returning null on emulator and device....but why?

I am using the following code to get a list of songs on my device. Eventually I'd like to do more with them but to just get started I want to find audio/music in an Android device.
I have used this code to query the media store and I keep getting a null cursor... I've checked out these stack overflow answers but their either not relevant or I don't understand them enough to implement them...
Would appreciate any help! Thanks in advance
public class AudioFinalActivity extends Activity {
private TextView tv;
private String res;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// link text view obj
tv = (TextView) findViewById(R.id.tv);
res = "";
String[] proj = { MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Artists.ARTIST };
// managed query doesn't need startManagingCursor called on the
Cursor c = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
proj, null, null, null);
// ContentResolver contentResolver = getContentResolver();
// String[] columns = { MediaColumns.TITLE, AudioColumns.DURATION,
// MediaColumns.DATA
// // add more columns if you want to fetch more data
// };
//
// Cursor c = contentResolver.query(
// MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, columns, null,
// null, null);
if (c != null) {
Log.d("AFA", "Cursor returned NULL");
} else if (c.getCount() < 1) {
Log.d("AFA", "Cursor query is empty.. :( ...");
} else {
// do stuff with our content...
while (c.moveToNext()) {
//String title = c.getString(c
.getColumnIndex(MediaColumns.TITLE));
//Long duration = c.getLong(c
.getColumnIndex(AudioColumns.DURATION));
//String data = c.getString(c
.getColumnIndex(MediaColumns.DATA));
//res += title + "\n";
res += c.getString(c.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)) + "\n";
tv.setText(res);
}
}
}
}
I the stock music player can play my phones audio just fine..
EDIT:
I just removed my checking for the cursor being empty and for the cursor being null and I seem to get a result.. strange why the cursor is null yet the while(c.MoveToNext())... returns values... hmmm
your checking is if (c != null) {}, but I suppose it is if (c == null) {} (if you are checking the cursor being null)

Why content provider returns null values for phone number?

I want to read contact numbers from my android phone. I used content provider for that, but i am getting null values. Here is my code :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt = (TextView)findViewById(R.id.txt);
String column[] = new String[]{People.NAME,People.NUMBER};
Cursor cur = this.managedQuery(People.CONTENT_URI, column, null, null, null);
if(cur.moveToFirst())
{
String name;
String number;
do
{
number = cur.getString(cur.getColumnIndex((People.NUMBER)));
str+="\n"+number;
}
while(cur.moveToNext());
txt.setText(str);
}
}
Thanks in advance.
I can't check it now but one thing I would change is that you do not need to use
cur.getColumnIndex((People.NUMBER))
because you already know that the column is the second one in your projection (so index=1)
Try this:
private Cursor getContactCursor(Context context) {
String[] projection = { ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER };
return context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, null);
}
and in onCreate()..
contactsCursor = getContactsCursor(this);
while (contactsCursor.moveToNext()) {
String name = contactsCursor.getString(0);
String number = contactsCursor.getString(1);
}

Categories

Resources