1

I have been developing an application which will get all the contacts from my phone contacts and send an SMS to selected contacts from that list. I am able to get all contacts with a check box for selection. I want that when I select contacts and press the "send message" button the message will automatically send with some text like "whats up!" etc

I need help getting the SMS to send to multiple contacts.

my Main Activity:

public class MainActivity extends  ListActivity {
    ArrayList<String> name1 = new ArrayList<String>();
    ArrayList<String> phno1 = new ArrayList<String>();
    protected static final String TAG = null;
    public String[] Contacts = {};
    public int[] to = {};
    public ListView myListView;


    //@SuppressWarnings("deprecation")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        final Button done_Button = (Button) findViewById(R.id.done_Button);
        final Button clear_Button =(Button) findViewById(R.id.clear_Button);
        Cursor mCursor = getContacts();

        startManagingCursor(mCursor);
        ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, mCursor,
                Contacts = new String[] {ContactsContract.Contacts.DISPLAY_NAME },
                to = new int[] { android.R.id.text1 });

        setListAdapter(adapter);
        myListView = getListView();
        myListView.setItemsCanFocus(false);
        myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        clear_Button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(),"Selection Cleared", Toast.LENGTH_SHORT).show();
                ClearSelections();
            }
        });

        /** When 'Done' Button Pushed: **/

        done_Button.setOnClickListener(new View.OnClickListener() {

            public void onClick (View v){   
                String name = null;
                String number = null;
                long [] ids = myListView.getCheckedItemIds();
                for(long id : ids) {
                    Cursor contact = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, 
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id + "" }, null);
                    while(contact.moveToNext()){
                        name = contact.getString(contact.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        //name+=name;
                        number = contact.getString(contact.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        //number+=number;
                    }
                    Toast.makeText(getApplicationContext(), "Name: " +name + "\n" + "Number: " + number , Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    private void ClearSelections() {
        int count = this.myListView.getAdapter().getCount();
        for (int i = 0; i < count; i++) {
            this.myListView.setItemChecked(i, false);
        }
    }

    @SuppressWarnings("deprecation")
    private Cursor getContacts() {
        // Run query
        Uri uri = ContactsContract.Contacts.CONTENT_URI;
        String[] projection = new String[] { ContactsContract.Contacts._ID,
                                        ContactsContract.Contacts.DISPLAY_NAME};
        String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '"
                + ("1") + "'";
        String[] selectionArgs = null;
        String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
                + " COLLATE LOCALIZED ASC";

        return managedQuery(uri, projection, selection, selectionArgs,
                sortOrder);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }     
}
indivisible
  • 4,892
  • 4
  • 31
  • 50
Ali Ashiq
  • 124
  • 2
  • 12
  • do we know ur problem pls ? – Maveňツ Jul 14 '14 at 12:57
  • yes sure i want to send a simple text message on selected contacts! i am able to get all contacts in a list view with check box, now i want that when i select a contact and press send button the message will send on that contact. – Ali Ashiq Jul 14 '14 at 13:02
  • 1
    smsManager.sendTextMessage("MOBILE_NO", null, "SMS_BODY", null, null); – Maveňツ Jul 14 '14 at 13:03
  • i want to send text with default text body like whats up text. – Ali Ashiq Jul 14 '14 at 13:06
  • SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage("phoneNo", null, "sms message", null, null); – Ali Ashiq Jul 14 '14 at 13:08
  • i have tried this it giving me exception what will i do – Ali Ashiq Jul 14 '14 at 13:08
  • Take a look of this. It might be helpful for you:- http://stackoverflow.com/questions/14452808/sending-and-receiving-sms-and-mms-in-android-pre-kit-kat-android-4-4?rq=1 – Laxmeena Jul 14 '14 at 13:15

2 Answers2

2

You need to use SmsManager for sending sms. Below is code for your reference :

SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("phoneNo", null, "sms message", null, null); 

Apply this code on your send message button click listener.

VVB
  • 7,363
  • 7
  • 49
  • 83
  • 07-14 18:04:48.683: E/AndroidRuntime(26749): FATAL EXCEPTION: main 07-14 18:04:48.683: E/AndroidRuntime(26749): java.lang.NullPointerException 07-14 18:04:48.683: E/AndroidRuntime(26749): at com.android.internal.telephony.gsm.SmsMessage.getSubmitPduHead(SmsMessage.java:660) – Ali Ashiq Jul 14 '14 at 13:05
  • 2
    have you added below permission in your manifest & put phone number & message. If you still get error show your whole logcat. – VVB Jul 14 '14 at 13:06
  • Refer this tutorial: http://www.mkyong.com/android/how-to-send-sms-message-in-android/ – VVB Jul 14 '14 at 13:09
  • done message have been send. now how can i send message from selected contact from my contact list. I have contact list when i select contact from that list the message will sent automatically on these numbers – Ali Ashiq Jul 14 '14 at 13:14
  • thank you so much user3811114 for your quick reply please help me sir i want to send message on selected contact from my contacts – Ali Ashiq Jul 14 '14 at 13:15
  • 2
    When you get correct answer so you need to upvote to that user this is how stackoverflow works. You need to use arraylist for your requirement. Your arraylist will be having mobile numbers & pass that arraylist using foreach loop to sendMessage function for every number. – VVB Jul 14 '14 at 13:20
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/57310/discussion-between-ali-ashiq-and-user3811114). – Ali Ashiq Jul 15 '14 at 07:47
1
public class sos extends AppCompatActivity {
TextView t1,t2;
Button sos;
ImageView add;
LinearLayout l1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sos);
    setTitle("SOS");
    sos= findViewById(R.id.sos);
    add= findViewById(R.id.add);
    t2= findViewById(R.id.t2);
    t1= findViewById(R.id.t1);

    sos.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String s="";
            s=t2.getText().toString();
            Intent intent = new Intent(Intent.ACTION_SENDTO,Uri.parse("sms:"+s));
            intent.putExtra("sms_body", "Hello");
            startActivity(intent);

        }
    });
    //open contracts
    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent= new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
            startActivityForResult(intent,1);

        }
    });
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        Uri contactData = data.getData();
        Cursor c =  getContentResolver().query(contactData, null, null, null, null);
        if (c.moveToFirst()) {
            String phoneNumber="";
            String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
            //http://stackoverflow.com/questions/866769/how-to-call-android-contacts-list   our upvoted answer

            String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

            if ( hasPhone.equalsIgnoreCase("1"))
                hasPhone = "true";
            else
                hasPhone = "false" ;

        if (Boolean.parseBoolean(hasPhone))
            {
                Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
                while (phones.moveToNext())
                {
                    phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                }
                phones.close();
            }


            t1.setText("Name: "+name);
            t2.setText("Phone: "+phoneNumber);



          Log.d("curs", name + " num" + phoneNumber );
        }
        c.close();
    }
}

}

kiran bankar
  • 91
  • 1
  • 1