Skip to content Skip to sidebar Skip to footer

How To Select More Contacts From My Contact List To Send An Sms

Right now i am able to select only one contact from my contacts in my phone,i want to send sms more person in my contact list ,how can i send. Right now i cant add more contacts in

Solution 1:

You can get all contacts from the contact list and display it in a list. You can select the contacts using check box and click the button. Navigate to SendMessage activity and type the sms content and send message

I think there is a better way of dealing with checkboxes. For check box get selected item i followed the below link.

https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M

Also you can fetch columns that you only need. Below fetches all columns which is not good.

Cursorphones= cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);

get.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity" >

<ListView
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_above="@+id/button1"
   android:id="@+id/lv"/>
 <Button
     android:id="@+id/button1"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignParentBottom="true"
     android:layout_alignParentLeft="true"
     android:layout_marginLeft="44dp"
     android:text="Send" />

 </RelativeLayout>

MainActivity.java

public class MainActivity extends Activity implements OnItemClickListener{

ArrayList<String> name1 = newArrayList<String>();
ArrayList<String> phno1 = newArrayList<String>();
ArrayList<String> phno0 = newArrayList<String>();
MyAdapter ma ;
Button show,add;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    setContentView(R.layout.get);
    getAllCallLogs(this.getContentResolver());
    ListView lv= (ListView) findViewById(R.id.lv);
     ma = newMyAdapter();
    lv.setAdapter(ma);
    lv.setOnItemClickListener(this); 
    lv.setItemsCanFocus(false);
    lv.setTextFilterEnabled(true);
    // adding
    add = (Button) findViewById(R.id.button1);
    add.setOnClickListener(newOnClickListener()
    {

        @OverridepublicvoidonClick(View v) {
              StringBuilder checkedcontacts= newStringBuilder();
            System.out.println(".............."+ma.mCheckStates.size());
            for(inti=0; i < name1.size(); i++)

                {
                if(ma.mCheckStates.get(i)==true)
                {
                      phno0.add(phno1.get(i).toString()) ;
                     checkedcontacts.append(name1.get(i).toString());
                     checkedcontacts.append("\n");

                }
                else
                {
           System.out.println("..Not Checked......"+name1.get(i).toString());
                }


            }
                Toast.makeText(MainActivity.this, checkedcontacts,1000).show();
                Intentintent=newIntent(newIntent(MainActivity.this,SendMessage.class));
                intent.putStringArrayListExtra("name",phno0);
                startActivity(intent); 

        }       
    });


}

@OverridepublicvoidonItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    // TODO Auto-generated method stub
     ma.toggle(arg2);
}

publicvoidgetAllCallLogs(ContentResolver cr) {

    Cursorphones= cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
    while (phones.moveToNext())
    {
      String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
      StringphoneNumber= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
      System.out.println(".................."+phoneNumber); 
      name1.add(name);
      phno1.add(phoneNumber);
    }

    phones.close();
 }
classMyAdapterextendsBaseAdapterimplementsCompoundButton.OnCheckedChangeListener
{  private SparseBooleanArray mCheckStates;
   LayoutInflater mInflater;
    TextView tv1,tv;
    CheckBox cb;
    MyAdapter()
    {
        mCheckStates = newSparseBooleanArray(name1.size());
        mInflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @OverridepublicintgetCount() {
        // TODO Auto-generated method stubreturn name1.size();
    }

    @Overridepublic Object getItem(int position) {
        // TODO Auto-generated method stubreturn position;
    }

    @OverridepubliclonggetItemId(int position) {
        // TODO Auto-generated method stubreturn0;
    }

    @Overridepublic View getView(finalint position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View vi=convertView;
        if(convertView==null)
         vi = mInflater.inflate(R.layout.row, null); 
         TextView tv= (TextView) vi.findViewById(R.id.textView1);
         tv1= (TextView) vi.findViewById(R.id.textView2);
         cb = (CheckBox) vi.findViewById(R.id.checkBox1);
         tv.setText("Name :"+ name1.get(position));
         tv1.setText("Phone No :"+ phno1.get(position));
         cb.setTag(position);
         cb.setChecked(mCheckStates.get(position, false));
         cb.setOnCheckedChangeListener(this);

        return vi;
    }
     publicbooleanisChecked(int position) {
            return mCheckStates.get(position, false);
        }

        publicvoidsetChecked(int position, boolean isChecked) {
            mCheckStates.put(position, isChecked);
        }

        publicvoidtoggle(int position) {
            setChecked(position, !isChecked(position));
        }
    @OverridepublicvoidonCheckedChanged(CompoundButton buttonView,
            boolean isChecked) {
        // TODO Auto-generated method stub

         mCheckStates.put((Integer) buttonView.getTag(), isChecked);                 
    }       
}   
}

SendMessage.java

publicclassSendMessageextendsActivity {

EditText ed1,ed2;
ArrayList<String> sendlist = newArrayList<String>();
Button b1;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stubsuper.onCreate(savedInstanceState);
    setContentView(R.layout.sendmessage);
    ed1= (EditText)findViewById(R.id.editText1);
    ed2= (EditText)findViewById(R.id.editText2);
    Bundleextras= getIntent().getExtras();
    if(extras!=null)
    {
        sendlist = extras.getStringArrayList("name");
        if(sendlist!=null)
        {
        for(int i=0;i<sendlist.size();i++)
        {
            ed1.append(sendlist.get(i).toString());
            ed1.append(";");
        }
    }
    }
    else
    {
        Toast.makeText(getApplicationContext(), "null",
                Toast.LENGTH_LONG).show();
    }
    b1 = (Button) findViewById(R.id.button1);
    b1.setOnClickListener(newOnClickListener()
    {

        @OverridepublicvoidonClick(View v) {
            // TODO Auto-generated method stubfor(int i=0;i<sendlist.size();i++)
            {

                if(ed2.getText().length()>0)
                {
                  try {
                        SmsManagersmsManager= SmsManager.getDefault();

                        smsManager.sendTextMessage(sendlist.get(i).toString(), null, ed2.getText().toString(), null, null);

                        Toast.makeText(getApplicationContext(), "SMS Sent!",
                                    Toast.LENGTH_LONG).show();
                      } catch (Exception e) {
                        Toast.makeText(getApplicationContext(),
                            "SMS faild, please try again later!",
                            Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                      }
                }
            }

        }

    });
}   
}

sendmessage.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent" ><EditTextandroid:id="@+id/editText1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:layout_alignParentRight="true"android:layout_alignParentTop="true"android:layout_marginTop="18dp"android:ems="10" ><requestFocus /></EditText><EditTextandroid:id="@+id/editText2"android:layout_width="wrap_content"android:layout_height="200dp"android:layout_alignParentLeft="true"android:layout_alignParentRight="true"android:layout_below="@+id/editText1"android:layout_marginTop="62dp"android:ems="10" /><TextViewandroid:id="@+id/textView1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignTop="@+id/editText1"android:layout_centerHorizontal="true"android:text="Phone Numbers" /><TextViewandroid:id="@+id/textView2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/editText1"android:layout_centerHorizontal="true"android:layout_marginTop="37dp"android:text="Message" /><Buttonandroid:id="@+id/button1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignLeft="@+id/textView2"android:layout_alignParentBottom="true"android:text="Send" /></RelativeLayout>

You need to add these two permissions

<uses-permissionandroid:name="android.permission.READ_CONTACTS"/><uses-permissionandroid:name="android.permission.SEND_SMS" />

Edit:

Open SendMessage Activity first. Click the get button next to editext1. Navigate to MainActivity which displays all contacts and select using check boxes. Click send will finish the actiivty and retunn sms activity. You can see the selected contacts in editext 1. The rest is the same.

I have used startActivity for result. This more than i can do to help you. pls modify the same accordingly.

publicclassSendMessageextendsActivity {

EditText ed1,ed2;
static int ResultCode= 12;
ArrayList<String> sendlist = newArrayList<String>();
Button b1,b2;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stubsuper.onCreate(savedInstanceState);
    setContentView(R.layout.sendmessage);
    b2 = (Button) findViewById(R.id.button2);
    ed1= (EditText)findViewById(R.id.editText1);
    ed2= (EditText)findViewById(R.id.editText2);
    b1 = (Button) findViewById(R.id.button1);
    b2.setOnClickListener(newOnClickListener()
     {

    @OverridepublicvoidonClick(View v) {
        // TODO Auto-generated method stubIntent i = newIntent(SendMessage.this, MainActivity.class);
        startActivityForResult(i, ResultCode);
    }

 });

    b1.setOnClickListener(newOnClickListener()
    {

        @OverridepublicvoidonClick(View v) {
            // TODO Auto-generated method stubfor(int i=0;i<sendlist.size();i++)
            {

                if(ed2.getText().length()>0)
                {
                  try {
                        SmsManager smsManager = SmsManager.getDefault();

                        smsManager.sendTextMessage(sendlist.get(i).toString(), null, ed2.getText().toString(), null, null);

                        Toast.makeText(getApplicationContext(), "SMS Sent!",
                                    Toast.LENGTH_LONG).show();
                      } catch (Exception e) {
                        Toast.makeText(getApplicationContext(),
                            "SMS faild, please try again later!",
                            Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                      }
                }
            }

        }

    });
}


protectedvoidonActivityResult(int requestCode, int resultCode, Intent data) {

      if (requestCode == ResultCode) {

         if(resultCode == RESULT_OK){      
             sendlist  =data.getStringArrayListExtra("name");
             if(sendlist!=null)
                {
                for(int i=0;i<sendlist.size();i++)
                {
                    ed1.append(sendlist.get(i).toString());
                    ed1.append(";");
                }

         }
         if (resultCode == RESULT_CANCELED) {    

         }
      }
    }
}
}

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent" ><EditTextandroid:id="@+id/editText1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:layout_alignParentRight="true"android:layout_alignParentTop="true"android:layout_marginTop="18dp"android:ems="10" ><requestFocus /></EditText><EditTextandroid:id="@+id/editText2"android:layout_width="wrap_content"android:layout_height="200dp"android:layout_alignParentLeft="true"android:layout_alignParentRight="true"android:layout_below="@+id/editText1"android:layout_marginTop="62dp"android:ems="10" /><TextViewandroid:id="@+id/textView1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignTop="@+id/editText1"android:layout_centerHorizontal="true"android:text="Phone Numbers" /><TextViewandroid:id="@+id/textView2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/editText1"android:layout_centerHorizontal="true"android:layout_marginTop="37dp"android:text="Message" /><Buttonandroid:id="@+id/button1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignLeft="@+id/textView2"android:layout_alignParentBottom="true"android:text="Send" /><Buttonandroid:id="@+id/button2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignBaseline="@+id/textView2"android:layout_alignBottom="@+id/textView2"android:layout_alignParentRight="true"android:text="Get" /></RelativeLayout>

MainActivity

publicclassMainActivityextendsActivityimplementsOnItemClickListener{


ArrayList<String> name1 = newArrayList<String>();
ArrayList<String> phno1 = newArrayList<String>();
ArrayList<String> phno0 = newArrayList<String>();
MyAdapter ma ;
Button send;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    setContentView(R.layout.get);
    getAllCallLogs(this.getContentResolver());
    ListView lv= (ListView) findViewById(R.id.lv);
     ma = newMyAdapter();
    lv.setAdapter(ma);
    lv.setOnItemClickListener(this); 
    lv.setItemsCanFocus(false);
    lv.setTextFilterEnabled(true);
    send = (Button) findViewById(R.id.button1);
    send.setOnClickListener(newOnClickListener()
    {

        @OverridepublicvoidonClick(View v) {
              StringBuilder checkedcontacts= newStringBuilder();
            System.out.println(".............."+ma.mCheckStates.size());
            for(int i = 0; i < name1.size(); i++)

                {
                if(ma.mCheckStates.get(i)==true)
                {
                      phno0.add(phno1.get(i).toString()) ;
                     checkedcontacts.append(name1.get(i).toString());
                     checkedcontacts.append("\n");

                }
                else
                {
                    System.out.println("..Not Checked......"+name1.get(i).toString());
                }


            }
                Toast.makeText(MainActivity.this, checkedcontacts,1000).show();
                Intent returnIntent = newIntent();
                 returnIntent.putStringArrayListExtra("name",phno0);
                 setResult(RESULT_OK,returnIntent);     
                 finish();

        }       
    });
}

@OverridepublicvoidonItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    // TODO Auto-generated method stub
     ma.toggle(arg2);
}

publicvoidgetAllCallLogs(ContentResolver cr) {

    Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
    while (phones.moveToNext())
    {
      String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
      String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
      System.out.println(".................."+phoneNumber); 
      name1.add(name);
      phno1.add(phoneNumber);
    }

    phones.close();
 }
classMyAdapterextendsBaseAdapterimplementsCompoundButton.OnCheckedChangeListener
{  privateSparseBooleanArray mCheckStates;
   LayoutInflater mInflater;
    TextView tv1,tv;
    CheckBox cb;
    MyAdapter()
    {
        mCheckStates = newSparseBooleanArray(name1.size());
        mInflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Overridepublic int getCount() {
        // TODO Auto-generated method stubreturn name1.size();
    }

    @OverridepublicObjectgetItem(int position) {
        // TODO Auto-generated method stubreturn position;
    }

    @Overridepublic long getItemId(int position) {
        // TODO Auto-generated method stubreturn0;
    }

    @OverridepublicViewgetView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stubView vi=convertView;
        if(convertView==null)
         vi = mInflater.inflate(R.layout.row, null); 
         tv= (TextView) vi.findViewById(R.id.textView1);
         tv1= (TextView) vi.findViewById(R.id.textView2);
         cb = (CheckBox) vi.findViewById(R.id.checkBox1);
         tv.setText("Name :"+ name1.get(position));
         tv1.setText("Phone No :"+ phno1.get(position));
         cb.setTag(position);
         cb.setChecked(mCheckStates.get(position, false));
         cb.setOnCheckedChangeListener(this);

        return vi;
    }
     publicbooleanisChecked(int position) {
            return mCheckStates.get(position, false);
        }

        publicvoidsetChecked(int position, boolean isChecked) {
            mCheckStates.put(position, isChecked);
        }

        publicvoidtoggle(int position) {
            setChecked(position, !isChecked(position));
        }
    @OverridepublicvoidonCheckedChanged(CompoundButton buttonView,
            boolean isChecked) {
        // TODO Auto-generated method stub

         mCheckStates.put((Integer) buttonView.getTag(), isChecked);                 
    }       
}   
} 

row.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent" ><TextViewandroid:id="@+id/textView1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:layout_alignParentTop="true"android:layout_marginLeft="15dp"android:layout_marginTop="34dp"android:text="TextView" /><TextViewandroid:id="@+id/textView2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignBottom="@+id/checkBox1"android:layout_alignLeft="@+id/textView1"android:text="TextView" /><CheckBoxandroid:id="@+id/checkBox1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentRight="true"android:layout_below="@+id/textView1"android:layout_marginRight="22dp"android:layout_marginTop="23dp" />
 </RelativeLayout 

Manifest file

<?xml version="1.0" encoding="utf-8"?><manifestxmlns:android="http://schemas.android.com/apk/res/android"package="com.example.sendsmstoall"android:versionCode="1"android:versionName="1.0" ><uses-sdkandroid:minSdkVersion="8"android:targetSdkVersion="17" /><uses-permissionandroid:name="android.permission.READ_CONTACTS"/><uses-permissionandroid:name="android.permission.SEND_SMS" /><applicationandroid:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme" ><activityandroid:name="com.example.sendsmstoall.SendMessage"android:label="@string/app_name" ><intent-filter><actionandroid:name="android.intent.action.MAIN" /><categoryandroid:name="android.intent.category.LAUNCHER" /></intent-filter></activity><activityandroid:name=".MainActivity"android:label="@string/app_name" ></activity></application></manifest>

Post a Comment for "How To Select More Contacts From My Contact List To Send An Sms"