0

first i'm fetching all messages to my app to be store in listview then I'm selecting messages from listview using checkboxes and wish to send these selected sms to a single number that is predefined and wish to use the selected sms as body of message to be send to single no. but the problem is that the message sent contains complete listview messages not the selected one. So please someone correct me where i'm wrong in code as i wish to send only selected messages not the complete listview items(messages)


public class MainActivity extends Activity implements OnItemClickListener, OnClickListener{

Button send;
ListView listViewSMS;
Cursor cursor;
SMSListAdapter smsListAdapter;
Context context;
SharedPreferences prefs=null;
ArrayAdapter<SMSListModel> adapter;
List<SMSListModel> list = new ArrayList<SMSListModel>();
TextView textViewSMSSender, textViewSMSBody;
int i;
int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    context=this;
    listViewSMS=(ListView)findViewById(R.id.lvSMS);

    send = (Button)findViewById(R.id.btnproperty);
    send.setOnClickListener(this);

    textViewSMSSender=(TextView)findViewById(R.id.tvSMSSend);
    textViewSMSBody=(TextView)findViewById(R.id.tvSMSBody);

    cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);

    smsListAdapter = new SMSListAdapter(this,getModel());
    listViewSMS.setAdapter(smsListAdapter);
    listViewSMS.setOnItemClickListener(this);


}
@Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
    TextView label = (TextView) v.getTag(R.id.tvSMSSend);
    CheckBox checkbox = (CheckBox) v.getTag(R.id.cbSelect);
    Toast.makeText(v.getContext(), label.getText().toString()+" "+isCheckedOrNot(checkbox), Toast.LENGTH_LONG).show();      
}

private String isCheckedOrNot(CheckBox checkbox) {
    if(checkbox.isChecked())
        return "is checked";
    else
        return "is not checked";
}

private List<SMSListModel> getModel() {

    if(cursor.getCount()>0){
        for(i=0;i<cursor.getCount();i++){
            if(cursor.moveToPosition(i)){
                list.add(new SMSListModel(cursor.getString(cursor.getColumnIndex("address")),cursor.getString(cursor.getColumnIndex("body"))));
            }
        }
    }


    return list;
}
@Override
public void onClick(View v) {



    if( v == send){
        mDialog();

    }



public void mDialog(){



     // Show The Dialog with Selected SMS 
     AlertDialog dialog = new AlertDialog.Builder(context).create();
     dialog.setTitle("Message App");
     dialog.setIcon(android.R.drawable.ic_dialog_info);
     dialog.setMessage("Count : ");
     dialog.setButton(DialogInterface.BUTTON_POSITIVE, "ok",
             new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) 
         {
             String phoneNo = "111";
             if(list.size()>0){
                 for(i=0;i<list.size();i++){
                     if(list.get(i).isSelected()){

                         try{
                             SmsManager smsManager = SmsManager.getDefault();
                             StringBuilder builder = new StringBuilder();
                             for(SMSListModel p: list){
                                 builder.append(p.toString());
                                 builder.append('\n');
                             }
                            String sms = builder.toString();
                             smsManager.sendTextMessage(phoneNo, null, sms, 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();

                         }
                         dialog.dismiss();

                 }
              }
            }
         }
     });

     dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", 
            new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getApplicationContext(), "SMS not Sent",Toast.LENGTH_LONG).show();
                        dialog.dismiss();

                    }
                });
     dialog.show();

}

public class SMSListAdapter extends ArrayAdapter<SMSListModel> {

private final List<SMSListModel> list;
private final Activity mContext;
boolean checkAll_flag = false;
boolean checkItem_flag = false;

public SMSListAdapter(Activity context,List<SMSListModel> list) 
{
    super(context, R.layout.listview_each_item, list);
    mContext = context;
    this.list = list;
}

static class ViewHolder {
    protected TextView textAddress;
    protected TextView textBody;
    protected CheckBox checkbox;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    ViewHolder viewHolder = null;
    if (convertView == null) {
        LayoutInflater inflator = mContext.getLayoutInflater();
        convertView = inflator.inflate(R.layout.listview_each_item, null);
        viewHolder = new ViewHolder();
        viewHolder.textAddress = (TextView) convertView.findViewById(R.id.tvSMSSend);
        viewHolder.textBody = (TextView) convertView.findViewById(R.id.tvSMSBody);
        viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.cbSelect);
        viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        int getPosition = (Integer) buttonView.getTag();  // Here we get the position that we have set for the checkbox using setTag.
                        list.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
                    }
                });
        convertView.setTag(viewHolder);
        convertView.setTag(R.id.tvSMSSend, viewHolder.textAddress);
        convertView.setTag(R.id.tvSMSBody, viewHolder.textBody);
        convertView.setTag(R.id.cbSelect, viewHolder.checkbox);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }
    viewHolder.checkbox.setTag(position); // This line is important.

    viewHolder.textAddress.setText(list.get(position).getAddress());
    viewHolder.textBody.setText(list.get(position).getBody());
    viewHolder.checkbox.setChecked(list.get(position).isSelected());    

    return convertView;
}

public class SMSListModel {

private String address;
String body;
private boolean selected;

public SMSListModel(String address, String body) {
    this.address = address;
    this.body = body;
}

public String getAddress() {
    return address;
}

public String getBody() {
    return body;
}

public boolean isSelected() {
    return selected;
}

public void setSelected(boolean selected) {
    this.selected = selected;
}

public String toString(){

    return body;
}}
Android beginner
  • 245
  • 2
  • 6
  • 22
  • What u want actually? be more specific – M D Jan 29 '14 at 10:16
  • I want to select multiple rows and perform delete or send all to specific no @ MD – Android beginner Jan 29 '14 at 10:24
  • Go to this link for your achievement [multiple-row-item-listview](http://sunil-android.blogspot.in/2013/11/multiple-row-item-deleted-from-listview.html) and [android-multiple-selection-listview/](http://theopentutorials.com/tutorials/android/listview/android-multiple-selection-listview/) – M D Jan 29 '14 at 10:27
  • If you want to select multiple rows then you should use multiple check box selection. – Piyush Jan 29 '14 at 10:49

2 Answers2

0

May I know why you want to select multiple rows. I mean what exact action you want to perform by selecting multiple rows?

Here is the updated code for you. Please let me know in case you didn't get any code:

    ---------------
    package com.example.multiselectlist;

    import java.util.ArrayList;
    import java.util.List;

    import android.app.Activity;
    import android.content.Context;
    import android.database.Cursor;
    import android.net.Uri;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.CheckBox;
    import android.widget.ListView;
    import android.widget.TextView;
    import android.widget.Toast;

    public class MainActivity extends Activity implements OnItemClickListener, OnClickListener{

        Button btnDelete;
        ListView listViewSMS;
        Cursor cursor;
        SMSListAdapter smsListAdapter;
        Context context;

        ArrayAdapter<SMSListModel> adapter;
        List<SMSListModel> list = new ArrayList<SMSListModel>();


        int count = 0;
        @Override
        protected void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            context=this;
            listViewSMS=(ListView)findViewById(R.id.lvSMS);
            btnDelete = (Button)findViewById(R.id.buttonDelete);

            cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);

            smsListAdapter = new SMSListAdapter(this,getModel());
            listViewSMS.setAdapter(smsListAdapter);
            listViewSMS.setOnItemClickListener(this);

            btnDelete.setOnClickListener(this);
        }
        @Override
        public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
            TextView label = (TextView) v.getTag(R.id.tvSMSSend);
            CheckBox checkbox = (CheckBox) v.getTag(R.id.cbSelect);
            Toast.makeText(v.getContext(), label.getText().toString()+" "+isCheckedOrNot(checkbox), Toast.LENGTH_LONG).show();      
        }

        private String isCheckedOrNot(CheckBox checkbox) {
            if(checkbox.isChecked())
                return "is checked";
            else
                return "is not checked";
        }

        private List<SMSListModel> getModel() {

            if(cursor.getCount()>0){
                for(int i=0;i<cursor.getCount();i++){
                    if(cursor.moveToPosition(i)){
                        list.add(new SMSListModel(cursor.getString(cursor.getColumnIndex("address")),cursor.getString(cursor.getColumnIndex("body"))));
                    }
                }
            }


            return list;
        }
        @Override
        public void onClick(View v) {
            int id = v.getId();

            switch(id){
                case R.id.buttonDelete:
                    if(list.size()>0){
                        for(int i=0;i<list.size();i++){
                            if(list.get(i).isSelected()){
                                list.remove(i);
                            }
                        }

                        smsListAdapter = new SMSListAdapter(this,list);
                        smsListAdapter.notifyDataSetChanged();
                        listViewSMS.setAdapter(smsListAdapter);
                    }
                    break;
                    case R.id.buttonSend:
 String contactNum = "+123456789";
            String messageList = "";
            if(list.size()>0){
                for(int i=0;i<list.size();i++){
                    if(list.get(i).isSelected()){
                        if(messageList.equals(""))
                            messageList = list.get(i).getBody();
                        else
                            messageList = messageList+";"+list.get(i).getBody();
                    }
                }
                Log.v("messageList",""+messageList);
                Uri sendSmsTo = Uri.parse("smsto:" + contactNum);
                Log.d("sendSmsTo",""+sendSmsTo);
                Intent intent = new Intent(android.content.Intent.ACTION_SENDTO, sendSmsTo);
                intent.putExtra("sms_body", messageList);
                startActivityForResult(intent, 100);    
            }

            }

        }
    }

SMSListModel class:

    package com.example.multiselectlist;

    public class SMSListModel {

        private String address;
        String body;
        private boolean selected;

        public SMSListModel(String address, String body) {
            this.address = address;
            this.body = body;
        }

        public String getAddress() {
            return address;
        }

        public String getBody() {
            return body;
        }

        public boolean isSelected() {
            return selected;
        }

        public void setSelected(boolean selected) {
            this.selected = selected;
        }
    }

SMSListAdapter class: package com.example.multiselectlist;

    import java.util.List;

    import android.app.Activity;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.CheckBox;
    import android.widget.CompoundButton;
    import android.widget.TextView;

    public class SMSListAdapter extends ArrayAdapter<SMSListModel> {

        private final List<SMSListModel> list;
        private final Activity mContext;
        boolean checkAll_flag = false;
        boolean checkItem_flag = false;

        public SMSListAdapter(Activity context,List<SMSListModel> list) 
        {
            super(context, R.layout.listview_each_item, list);
            mContext = context;
            this.list = list;
        }

        static class ViewHolder {
            protected TextView textAddress;
            protected TextView textBody;
            protected CheckBox checkbox;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder viewHolder = null;
            if (convertView == null) {
                LayoutInflater inflator = mContext.getLayoutInflater();
                convertView = inflator.inflate(R.layout.listview_each_item, null);
                viewHolder = new ViewHolder();
                viewHolder.textAddress = (TextView) convertView.findViewById(R.id.tvSMSSend);
                viewHolder.textBody = (TextView) convertView.findViewById(R.id.tvSMSBody);
                viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.cbSelect);
                viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                            @Override
                            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                                int getPosition = (Integer) buttonView.getTag();  // Here we get the position that we have set for the checkbox using setTag.
                                list.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
                            }
                        });
                convertView.setTag(viewHolder);
                convertView.setTag(R.id.tvSMSSend, viewHolder.textAddress);
                convertView.setTag(R.id.tvSMSBody, viewHolder.textBody);
                convertView.setTag(R.id.cbSelect, viewHolder.checkbox);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.checkbox.setTag(position); // This line is important.

            viewHolder.textAddress.setText(list.get(position).getAddress());
            viewHolder.textBody.setText(list.get(position).getBody());
            viewHolder.checkbox.setChecked(list.get(position).isSelected());    

            return convertView;
        }

    }

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"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context=".MainActivity" >

         <Button
            android:id="@+id/buttonDelete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:text="Delete" />

        <ListView
            android:id="@+id/lvSMS"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/buttonDelete" >
        </ListView>

    </RelativeLayout>

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <CheckBox
            android:id="@+id/cbSelect"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true" />

         <TextView
            android:id="@+id/tvSMSSend"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/cbSelect"
            android:layout_marginLeft="10dp"
            android:layout_toRightOf="@+id/cbSelect"
            android:text="9998698700" />

        <TextView
            android:id="@+id/tvSMSBody"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/tvSMSSend"
            android:layout_marginLeft="10dp"
            android:layout_toRightOf="@+id/tvSMSSend"
            android:text="body" />

    </RelativeLayout>
Shayan Pourvatan
  • 11,898
  • 4
  • 42
  • 63
sUndeep
  • 362
  • 3
  • 16
  • Alright. You can do like: 1. Keep checkbox (avoid recycling issue) on each list item. 2. Create a Global variable ArrayList which will store selected ids. 3. On checkbox clicked, store each ids. 4. Put a delete button above the layout on clicking of which delete your stored ids. If you still didn't get me share your code, I will do it for you. – sUndeep Jan 29 '14 at 10:25
  • I am updating my SDK manager. I will get back to you after 2-3 hours. – sUndeep Jan 29 '14 at 10:32
  • Please find the necessary code edited above. Please let me know in case you didn't get any part from that. – sUndeep Jan 30 '14 at 07:22
  • Thanks :) Please mark this post as resolved so that other can take benifit of it. – sUndeep Jan 30 '14 at 09:39
  • To see the code for "SMS to multiple contacts/phone numbers", please check the line from "case R.id.buttonSend:". I have edited the code. – sUndeep Jan 30 '14 at 11:48
  • This time you try yourself and let me know :). I will give a +1 to you if you do it. – sUndeep Jan 30 '14 at 13:26
  • it uses predefined number and there is a problem in sms body of new message it take complete inbox messages but not the selected one can you resolve this – Android beginner Jan 31 '14 at 08:05
  • Okay. I will resolve. But please answer in case a user select multiple message then what should happen? Will message body of all selected message will be sent? – sUndeep Jan 31 '14 at 08:13
  • yes only selected message body need to be sent but with this all inbox message body are sent – Android beginner Jan 31 '14 at 09:16
  • Okay I understand. It can be done that if a user select one message that particular message can be sent. But what if if you check on multiple messages on the list and press send button? – sUndeep Feb 02 '14 at 01:42
  • then all the checked messages need to be send – Android beginner Feb 02 '14 at 05:12
  • messages with Phone number are displaying instead of their name saved in contact list – Android beginner Feb 27 '14 at 11:05
0

You can always use:

yourListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

To choose multiple items, remember that its interface depend on you creating it.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item 
    android:state_pressed="true"
    android:drawable="@color/white" />
<item
    android:state_selected="true"
    android:drawable="@drawable/list_item_bg_selected" />
<item 
    android:drawable="@color/list_bg" />
</selector>
Aashir
  • 2,621
  • 4
  • 21
  • 37
  • how to change background color of selected row @ Aashir – Android beginner Jan 29 '14 at 10:34
  • Answer updated. You set that XML as the background for your row snd it will adjust accordingly, also change the backgrounds to the ones you have. – Aashir Jan 29 '14 at 10:46
  • do i need to create another xml in layout folder for the above code – Android beginner Jan 29 '14 at 10:50
  • In the drawable folder. – Aashir Jan 29 '14 at 10:52
  • with what name in drawable folder and what code to write in main xml where listview is declare and what is "@drawable/list_item_bg_selcted" – Android beginner Jan 29 '14 at 11:01
  • The name is your choice.. set it as the background of your custom row view xml, like android:background="@drawable/the name you chose". And like I said,replace them with the color / Image you want the row to have when its selected and when it's not. – Aashir Jan 29 '14 at 11:04