Anirudh
Anirudh

Reputation: 3428

ListView with checkbox using multichoice in android

here is my code, when i click button "b" a listview populates with a checkbox for each item, now i want to get items with check box checked into another activity, how do i acheive this, i came half way i'm confused how to do the remaining part

here is my code XML file :

<Button
    android:id="@+id/b"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Pick contact" />

<ListView
    android:choiceMode="multipleChoice"
    android:id="@+id/lv"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

This is java code:

import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
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.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {
Button b;
int PICK_CONTACT;
ArrayList<String> al;
ArrayAdapter<String> aa;
ListView lv;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    b = (Button) findViewById(R.id.b);

    lv = (ListView) findViewById(R.id.lv);
    al = new ArrayList<String>();



    b.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            displaycontacts();
            System.out.println("size" + al.size());
            aa = new ArrayAdapter<String>(MainActivity.this,
                        android.R.layout.simple_list_item_multiple_choice, al);
            lv.setAdapter(aa);


        }
    });

    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position ,long arg3) 
        {

            //here i should get the item which is checked
        }
    });

}

public void displaycontacts() {
    try {
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
                null, null, null);

        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {

                String name = cur
                        .getString(cur
                                .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                if (Integer
                        .parseInt(cur.getString(cur
                                .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                    System.out.println("name : " + name);
                    al.add(name);

                }
            }

        }

    } catch (Exception e) {
        System.out.println("Error:::::::::::::::::::" + e);
    }

}
}

Upvotes: 3

Views: 16390

Answers (3)

Cabezas
Cabezas

Reputation: 10767

Try this example, you need:

  • Interface
  • Data (String text, boolean selected)
  • Adapter
  • Fragment or Activity
  • list_item.xml

You can start with data:

public class MultipleData {
    private String text;
    private boolean selected;

    public MultipleData(String text, boolean selected) {
        this.text = text;
        this.selected = selected;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public boolean isSelected() {
        return selected;
    }

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

list_item.xml

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

    <TextView
        android:id="@+id/list_item_text"
        android:layout_width="match_parent"
        android:layout_height="90dp"
        android:text="@string/app_name"
        android:layout_toLeftOf="@+id/list_item_check_button"
        android:gravity="center"/>

    <RadioButton
        android:id="@+id/list_item_check_button"
        android:layout_width="wrap_content"
        android:layout_height="90dp"
        android:layout_alignParentRight="true"
        android:checked="false"
        android:clickable="false"
        android:focusable="false" />

</RelativeLayout>

activity_mail.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:id="@+id/fragment_multiple_list_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

</RelativeLayout>

Adapter

public class MultipleAdapter extends BaseAdapter implements SelectedIndex {

    private final Context mContext;
    List<MultipleData> mList;

    @Override
    public void setSelectedIndex(int position) {

        if (mList.get(position).isSelected()) {
            mList.get(position).setSelected(false);
        } else {
            mList.get(position).setSelected(true);
        }
    }

    static class ViewHolder {
        TextView mTextView;
        RadioButton mRadioButton;
    }

    public MultipleAdapter(Context context, List<MultipleData> list) {
        this.mContext = context;
        this.mList = list;
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

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

        if (rowView == null) {
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            rowView = inflater.inflate(R.layout.list_item, null);

            ViewHolder viewHolder = new ViewHolder();
            viewHolder.mTextView = (TextView) rowView.findViewById(R.id.list_item_text);
            viewHolder.mRadioButton = (RadioButton) rowView.findViewById(R.id.list_item_check_button);

            rowView.setTag(viewHolder);
        }

        // fill data
        ViewHolder holder = (ViewHolder) rowView.getTag();
        holder.mTextView.setText(mList.get(position).getText());
        holder.mRadioButton.setChecked(mList.get(position).isSelected());

        return rowView;
    }

}

Interface

public interface SelectedIndex {
    void setSelectedIndex(int position);
}

In your fragment or activity:

public class MultipleFragment extends Fragment implements AdapterView.OnItemClickListener {

    MultipleAdapter mAdapter;

    public MultipleFragment() {
        // Required empty public constructor
    }

    public static MultipleFragment newInstance() {
        return new MultipleFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_multiple, container, false);
        ListView listView = (ListView) view.findViewById(R.id.fragment_multiple_list_view);

        MultipleData android = new MultipleData("Android", false);
        MultipleData iPhone = new MultipleData("iPhone", false);
        MultipleData windowsMobile = new MultipleData("WindowsMobile", false);

        MultipleData blackberry = new MultipleData("Blackberry", false);
        MultipleData webOS = new MultipleData("WebOS", false);
        MultipleData ubuntu = new MultipleData("Ubuntu", false);

        MultipleData windows7 = new MultipleData("Windows7", false);
        MultipleData max = new MultipleData("Max OS X", false);
        MultipleData linux = new MultipleData("Linux", false);

        MultipleData os = new MultipleData("OS/2", false);
        MultipleData symbian = new MultipleData("Symbian", false);

        List<MultipleData> list = new ArrayList<>();
        list.add(0, android);
        list.add(1, iPhone);
        list.add(2, windowsMobile);

        list.add(3, blackberry);
        list.add(4, webOS);
        list.add(5, ubuntu);

        list.add(6, windows7);
        list.add(7, max);
        list.add(8, linux);

        list.add(9, os);
        list.add(10, symbian);

        mAdapter = new MultipleAdapter(getActivity(),list);
        listView.setAdapter(mAdapter);
        listView.setOnItemClickListener(this);
        return view;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        mAdapter.setSelectedIndex(position);
        mAdapter.notifyDataSetChanged();
    }
}

you can check this example in GitHub and this blog

Upvotes: 0

Veerababu Medisetti
Veerababu Medisetti

Reputation: 2755

try this link for list view with multiple choice. http://android-coding.blogspot.in/2011/09/listview-with-multiple-choice.html. Let me know your problem is resolved or not?

Upvotes: 6

cketti
cketti

Reputation: 1377

You need more information than the display name to identify a contact. So consider using CursorAdapter to get and hold on to that information.

If you are working with contacts you might want to use ContactsContract.ContactsColumns.LOOKUP_KEY to identify contacts. In that case...

  • use ListView.getCheckedItemPositions() to get the positions of checked items
  • then ListView.getItemAtPosition(int) to get the Cursor moved to that position
  • get the contact's lookup value

    cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
    
  • and put the array/list of lookup values in the extras of the intent used to start the activity.

Upvotes: 1

Related Questions