Search code examples
androidandroid-alertdialogmultichoiceitems

multiselect choice alert dialog only changes value of last item on clicking an item android


I have a multichoice alert dialog which displays an arraylist properly in a list with checkbox in each row.I want to change the value of the checked item in the list ie...if it is checked it should be 1 else 0.The problem is on clicking it only fetches the last item in the list and changes its value

 alertdialogbuilder = new AlertDialog.Builder(FormBuilderActivity.this);

    final boolean[] Selectedtruefalse = new boolean[multiSelectPopulationList[0].size()];

    for(int x=0;x<multiSelectPopulationList[0].size();x++)
    {
        if(multiSelectPopulationList[0].get(x).getValue()==0)
        {
            Selectedtruefalse[x]=false;
        }
        else
        {
            Selectedtruefalse[x]=true;
        }
    }

    final ArrayList<MultiSelectModel> ItemsIntoList;

    ItemsIntoList = new ArrayList<>();
    ItemsIntoList.clear();
    ItemsIntoList.addAll(multiSelectPopulationList[0]);

    final String[] AlertDialogItems = new String[multiSelectPopulationList[0].size()];
    for(int z=0;z<multiSelectPopulationList[0].size();z++)
    {
        AlertDialogItems[z]=multiSelectPopulationList[0].get(z).getPopulationListItem();
    }

    alertdialogbuilder.setMultiChoiceItems(AlertDialogItems, Selectedtruefalse, new DialogInterface.OnMultiChoiceClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which, boolean isChecked) {
            if(multiSelectPopulationList[0].get(which).getValue()==0)
            {
                multiSelectModel.setValue(1);
                multiSelectPopulationList[0].set(which, multiSelectModel);
                Log.d("Multisel["+which+"]rowlabel",multiSelectPopulationList[0].get(which).getName());
                Log.d("Multisel["+which+"]rowId",multiSelectPopulationList[0].get(which).getRowId());
                Log.d("Multisel["+which+"]optionValue",multiSelectPopulationList[0].get(which).getPopulationListItem());
                Log.d("Multisel["+which+"]checkValue",String.valueOf(multiSelectPopulationList[0].get(which).getValue()));

            }
            else
            {
                multiSelectModel.setValue(1);
                multiSelectPopulationList[0].set(which, multiSelectModel);
                Log.d("Multisel["+which+"]rowlabel",multiSelectPopulationList[0].get(which).getName());
                Log.d("Multisel["+which+"]rowId",multiSelectPopulationList[0].get(which).getRowId());
                Log.d("Multisel["+which+"]optionValue",multiSelectPopulationList[0].get(which).getPopulationListItem());
                Log.d("Multisel["+which+"]checkValue",String.valueOf(multiSelectPopulationList[0].get(which).getValue()));
            }



        }
    });

Solution

  • I have tried custom multiselect pop up dialog with search option.

    Create class name with MultiSelect.java

    public class MultiSelect {
    
        private int id;
        private String name;
        private boolean isSelected;
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public boolean isSelected() {
            return isSelected;
        }
    
        public void setSelected(boolean selected) {
            isSelected = selected;
        }
    }
    

    create xml file with name pop_up_list.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="10dp">
    
        <EditText
            android:id="@+id/etxt_search"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/rounded_edge"
            android:drawableLeft="@android:drawable/ic_search_category_default"
            android:visibility="gone" />
    
        <CheckBox
            android:id="@+id/chk_select_all"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Select All"
            android:textColor="@android:color/black"
            android:visibility="gone" />
    
        <ListView
            android:id="@+id/list_items"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_marginTop="10dp"
            android:layout_weight="1" />
    
        <android.support.v7.widget.RecyclerView
            android:id="@+id/list_recycle_items"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_marginTop="10dp"
            android:layout_weight="1"
            android:visibility="gone" />
    
        <Button
            android:id="@+id/btn_filter_select"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_gravity="center"
            android:layout_marginTop="10dp"
            android:background="@drawable/rounded_edge_orange"
            android:text="Select"
            android:textColor="@android:color/white" />
    
    </LinearLayout>
    

    create Adapter Class with name PrefStateAdapter.java

    import android.content.Context;
    import android.support.annotation.NonNull;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.BaseAdapter;
    import android.widget.CheckBox;
    import android.widget.CompoundButton;
    import android.widget.Filter;
    import android.widget.Filterable;
    import android.widget.TextView;
    
    import <your_project_package>.R;
    import <your_project_package>.MultiSelect;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class PrefStateAdapter extends BaseAdapter implements Filterable {
    
        private Context context;
        private List<MultiSelect> listState;
        private List<MultiSelect> tempStateList;
        private CityFilter cityFilter;
        ViewHolder holder = null;
    
        public PrefStateAdapter(Context context, List<MultiSelect> list) {
            this.context = context;
            this.listState = list;
            this.tempStateList = list;
        }
    
    
        @Override
        public int getCount() {
            return listState.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) {
            if (convertView == null) {
                LayoutInflater layoutInflator = LayoutInflater.from(context);
                convertView = layoutInflator.inflate(R.layout.row_pref_city, null);
                holder = new ViewHolder();
                holder.mTextView = (TextView) convertView.findViewById(R.id.txt_pref_city_name);
                holder.mCheckBox = (CheckBox) convertView.findViewById(R.id.chk_pref_city);
                holder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        MultiSelect m = listState.get((Integer) buttonView.getTag());
                        m.setSelected(isChecked);
    
                        for (int i = 0; i < tempStateList.size(); i++) {
                            MultiSelect multiSelect = tempStateList.get(i);
                            if (m.getId() == multiSelect.getId()) {
                                multiSelect.setSelected(isChecked);
                            }
                        }
    
                        notifyDataSetChanged();
                    }
                });
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.mCheckBox.setTag(position);
            MultiSelect m = listState.get((Integer) holder.mCheckBox.getTag());
            holder.mCheckBox.setTag(position);
            holder.mTextView.setText(m.getName());
    
    
            holder.mCheckBox.setChecked(m.isSelected());
    
            //holder.mCheckBox.setChecked((boolean) holder.mCheckBox.getTag(m.getId()));
    
    
            return convertView;
        }
    
        @Override
        public Filter getFilter() {
            if (cityFilter == null) {
                cityFilter = new CityFilter();
            }
            return cityFilter;
        }
    
        class CityFilter extends Filter {
    
    
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults results = new FilterResults();
                if (constraint != null && constraint.length() > 0) {
                    List<MultiSelect> filterList = new ArrayList<MultiSelect>();
                    for (int i = 0; i < tempStateList.size(); i++) {
                        if ((tempStateList.get(i).getName().toUpperCase())
                                .contains(constraint.toString().toUpperCase())) {
                            MultiSelect multiSelect = new MultiSelect();
                            multiSelect.setName(tempStateList.get(i).getName());
                            multiSelect.setId(tempStateList.get(i).getId());
                            multiSelect.setSelected(tempStateList.get(i).isSelected());
                            filterList.add(multiSelect);
                        }
                    }
                    results.count = filterList.size();
                    results.values = filterList;
                } else {
                    results.count = tempStateList.size();
                    results.values = tempStateList;
                }
                return results;
            }
    
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                listState = (List<MultiSelect>) results.values;
                //tempCityList = (List<MultiSelect>) results.values;
                notifyDataSetChanged();
            }
        }
    
        private class ViewHolder {
            private TextView mTextView;
            private CheckBox mCheckBox;
        }
    }
    

    finally method that will show multiselect pop up

    private void showDesignationPopUp(final List<MultiSelect> list) {
        final AlertDialog.Builder dialog = new AlertDialog.Builder(YourClassName.this);
        LayoutInflater inflater = LayoutInflater.from(YourClassName.this);
        //dialog.setCancelable(false);
        final View v = inflater.inflate(R.layout.pop_up_list, null);
    
        final ListView cityList = (ListView) v.findViewById(R.id.list_items);
        final EditText etxtSearch = (EditText) v.findViewById(R.id.etxt_search);
        final Button btnFilteSelect = (Button) v.findViewById(R.id.btn_filter_select);
    
        //If you don't want to use search option, comment below line
        etxtSearch.setVisibility(View.VISIBLE);
    
        final PrefStateAdapter adapter = new PrefStateAdapter(CandiPrefJobLocationNew.this, list);
    
        cityList.setAdapter(adapter);
    
        etxtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
            }
    
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                adapter.getFilter().filter(s);
            }
    
            @Override
            public void afterTextChanged(Editable s) {
    
            }
        });
    
        btnFilteSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //you can get selected item in this
            }
        });
    
        dialog.setView(v);
    
        ad2 = dialog.show();
    }
    

    This is working code, you need to change in drawable in xml file I hope this will help you Happy coding!!!! All the best!!