Search code examples
androidlistviewcheckboxcontactsandroid-contacts

How to get selected items in listview with checkbox on button click


I am trying to get contacts on a listview and get selected items on button click. I use custom adapter, but I don't know how to get the selected items.

I tries lots of different methods like setOnItemChangeListener to store change state items. But none working.

Here is the code,

package com.example.callblocker;

import java.util.ArrayList;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Checkable;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.Toast;

/**
 * Developed by Azharahmed
 */
public class MainActivity extends ListActivity {
    /** Called when the activity is first created. */

    private ArrayList<Contact> contact_list = null;
    private ProgressDialog mProgressDialog = null;
    private contactAdapter mContactAdapter = null;
    private Runnable mViewcontacts = null;

    private ArrayList<Contact> items;
    boolean[] isChecked;
    Cursor mCursor;
    ListView lv;
    Button blockSelectedBtn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        contact_list = new ArrayList<Contact>();
        lv = getListView();

        blockSelectedBtn = (Button)findViewById(R.id.button1);
        blockSelectedBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                for (int i = 0; i < mContactAdapter.getCount(); i++)
                {
                    Contact contact = mContactAdapter.getItem(i);
                    if (((Checkable) contact).isChecked())
                    {
                        Toast.makeText(MainActivity.this,
                                contact.getContactName() + " is Checked!!",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

        mViewcontacts = new Runnable() {
            @Override
            public void run() {
                getContacts();
            }
        };

        Thread thread = new Thread(null, mViewcontacts, "ContactReadBackground");
        thread.start();
        mProgressDialog = ProgressDialog.show(MainActivity.this,
                "Please Wait...", "Retriving Contacts...", true);
    }

    @SuppressWarnings("unused")
    private void getContacts() {

        try {

            String[] projection = new String[] {
                    ContactsContract.Contacts.DISPLAY_NAME,
                    ContactsContract.Contacts.HAS_PHONE_NUMBER,
                    ContactsContract.Contacts._ID };

            mCursor = managedQuery(ContactsContract.Contacts.CONTENT_URI,
                    projection, ContactsContract.Contacts.HAS_PHONE_NUMBER
                            + "=?", new String[] { "1" },
                    ContactsContract.Contacts.DISPLAY_NAME);

            while (mCursor.moveToNext()) {
                Contact contact = new Contact();

                String contactId = mCursor.getString(mCursor
                        .getColumnIndex(ContactsContract.Contacts._ID));
                contact.setContactName(mCursor.getString(mCursor
                        .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
                contact_list.add(contact);
            }
            isChecked = new boolean[mCursor.getCount()];

            for (int i = 0; i < isChecked.length; i++) {
                isChecked[i] = false;
            }

            this.mContactAdapter = new contactAdapter(this, R.layout.listview,
                    contact_list);
            lv.setAdapter(this.mContactAdapter);
            mCursor.close();

            runOnUiThread(returnRes);

        } catch (Exception e) {
            Log.d("getContacts", e.getMessage());
        }
    }

    public class contactAdapter extends ArrayAdapter<Contact> {

        public contactAdapter(Context context, int textViewResourceId,
                ArrayList<Contact> items1) {
            super(context, textViewResourceId, items1);
            items = items1;
        }

        @Override
        public View getView(final int position, View convertView,
                ViewGroup parent) {
            ViewHolder mViewHolder;

            mViewHolder = new ViewHolder();
            LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = vi.inflate(R.layout.listview, parent, false);
            mViewHolder.cb = (CheckBox) convertView.findViewById(R.id.checkBox);
            mViewHolder.cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    Toast.makeText(MainActivity.this, "item changed", Toast.LENGTH_LONG).show();

                }
            });
            convertView.setTag(mViewHolder);

            if (isChecked[position] == true)
                mViewHolder.cb.setChecked(true);
            else
                mViewHolder.cb.setChecked(false);
            mViewHolder.cb
                    .setOnCheckedChangeListener(new OnCheckedChangeListener() {

                        @Override
                        public void onCheckedChanged(CompoundButton buttonView,
                                boolean ischecked) {
                            if (buttonView.isChecked()) {
                                isChecked[position] = true;
                            } else {
                                isChecked[position] = false;
                            }
                        }
                    });

            Contact contacts = items.get(position);
            if (contacts != null) {
                if (mViewHolder.cb != null) {
                    mViewHolder.cb.setText(contacts.getContactName());
                }
            }

            return convertView;
        }
    }

    public class ViewHolder {
        CheckBox cb;
    }

    private Runnable returnRes = new Runnable() {

        @Override
        public void run() {
            if (mProgressDialog.isShowing())
                mProgressDialog.dismiss();
            mContactAdapter.notifyDataSetChanged();
        }
    };

   }

Here is one of the error code.

    12-13 16:36:02.407: E/AndroidRuntime(14885): FATAL EXCEPTION: main
12-13 16:36:02.407: E/AndroidRuntime(14885): java.lang.ClassCastException: com.example.callblocker.Contact
12-13 16:36:02.407: E/AndroidRuntime(14885):    at com.example.callblocker.MainActivity$2.onClick(MainActivity.java:62)
12-13 16:36:02.407: E/AndroidRuntime(14885):    at android.view.View.performClick(View.java:2552)
12-13 16:36:02.407: E/AndroidRuntime(14885):    at android.view.View$PerformClick.run(View.java:9229)
12-13 16:36:02.407: E/AndroidRuntime(14885):    at android.os.Handler.handleCallback(Handler.java:587)
12-13 16:36:02.407: E/AndroidRuntime(14885):    at android.os.Handler.dispatchMessage(Handler.java:92)
12-13 16:36:02.407: E/AndroidRuntime(14885):    at android.os.Looper.loop(Looper.java:130)
12-13 16:36:02.407: E/AndroidRuntime(14885):    at android.app.ActivityThread.main(ActivityThread.java:3701)
12-13 16:36:02.407: E/AndroidRuntime(14885):    at java.lang.reflect.Method.invokeNative(Native Method)
12-13 16:36:02.407: E/AndroidRuntime(14885):    at java.lang.reflect.Method.invoke(Method.java:507)
12-13 16:36:02.407: E/AndroidRuntime(14885):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
12-13 16:36:02.407: E/AndroidRuntime(14885):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
12-13 16:36:02.407: E/AndroidRuntime(14885):    at dalvik.system.NativeStart.main(Native Method)

Any hint or suggestion will be very helpful.


Solution

  • You could try using SparseBooleanArray to get the selected items (from positions). Similar stackoverflow questions with relevant answers:

    1. How to get Selected items from Multi Select List View
    2. How to get all checked items from a ListView?