Skip to content Skip to sidebar Skip to footer

Android List View Custom Adapter With Checkbox Multiple Selection And Search Listview

I Have implemented the ListView with Custom Adopter class and Multiple check box selection . Its working fine . After that I have given search the name in ListView. If I checked ro

Solution 1:

 @Override
        publicvoidonCheckedChanged(CompoundButton buttonView, boolean isChecked) {

          if(isChecked){

             group.setChecked(true);
             int pos = originalList.indexOf(group)
             originalList.get(pos).setChecked(true);
             fullUsers.get(position).setChecked(true);
           }else{

            group.setChecked(false);
            int pos = originalList.indexOf(group)
             originalList.get(pos).setChecked(true);
            fullUsers.get(position).setChecked(false);
           }

        }

Solution 2:

update your adapter use SparseBooleanArray

publicclassFullUserAdapterextendsArrayAdapter<FullUser> {
    private ArrayList<FullUser> originalList;
    private ArrayList<FullUser> fullUsers;
    private SubjectFilter filter;
    SparseBooleanArray booleanArray ;


    publicFullUserAdapter(Context context, int resource, ArrayList<FullUser> fullUsers) {
        super(context, resource, fullUsers);
        this.fullUsers = new ArrayList<FullUser>();
        this.fullUsers.addAll(fullUsers);
        this.originalList = new ArrayList<FullUser>();
        this.originalList.addAll(fullUsers);
        booleanArray = new SparseBooleanArray();

    }


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

        .
        .
        .

        final FullUser group =getItem(position);
        holder.groupid.setText(group.getId());
        holder.checkBox.setOnCheckedChangeListener(null);
        holder.checkBox.setChecked(booleanArray.get(group.getId().hashCode(),false));
         holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            publicvoidonCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            booleanArray.put(group.getId().hashCode(), isChecked);
            }
        });
        .
        .
        .
        return row;
    }

   public ArrayList<FullUser> getSelectedItems() {
         ArrayList<FullUser> list  = new ArrayList<>();
         for(FullUser group:fullUsers){
             if(booleanArray.get(group.getId().hashCode(), false)){
                 list.add(group);
             }
         }
         return list;

    };

    }

Solution 3:

<?xml version="1.0" encoding="utf-8"?><RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".dashboard.VoterListActivity"><ProgressBarandroid:id="@+id/reqprogressbar"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerHorizontal="true"android:layout_centerVertical="true"android:visibility="gone" /><ListViewandroid:id="@+id/voter_lv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_above="@+id/btn_show_me"android:divider="@null"/><Buttonandroid:id="@+id/btn_show_me"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_alignParentBottom="true"android:layout_marginLeft="10dp"android:layout_marginRight="10dp"android:layout_marginBottom="5dp"android:background="@drawable/n_btn"android:text="@string/add_family_numbers"android:visibility="gone"android:textColor="#ffffff"android:textSize="20sp" /></RelativeLayout>

Java Code

public Class  Actvity extendsAppCompatActivity {
ProgressBar progressBar;
ListView listView;
VoterDao voterDao;
String Token, Userid, Appid, Deviceid;
MenuItem searchview;
VoterListAdapter adapter;

String pid;
VoterDatum friend;
String value;
CheckBox mCheckBox;
Button btn_show_me;
ArrayList<VoterDatum> friends;
ListView1Adapter adapter1;
VoterDatum Model;
StringBuilder stringBuilder;
String name;

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_voter_list);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle(R.string.voter_list);
    stringBuilder = newStringBuilder();
    Token = Util.getStringFromSP(this, "token");
    Userid = Util.getStringFromSP(this, "user_id");
    Appid = Util.getStringFromSP(this, "app_id");
    Deviceid = Util.getStringFromSP(this, "device_id");

    initViews();
    getVoterData();

    btn_show_me.setOnClickListener(newView.OnClickListener() {
        @OverridepublicvoidonClick(View v) {

            inti=0;
            if (friends.size() == i) { //do nothing
            }
            while (friends.size() > i) {
                intcount= friends.size();
                Model = friends.get(i);

                if (Model.isChecked()) {
                    Log.i("ListActivity", "here" + friends.get(i).getCitizenId());
                    stringBuilder.append("," + friends.get(i).getCitizenId());
                    name = stringBuilder.toString();
                    StringjoinedString= Model.getCitizenId().toString();
                    Log.d("ls", "" + name);
                    name = name.substring(1);
                    Log.d("fs", name);
                    sendToServer();

                }


                i++; // rise i
            }


        }
    });
}

privatevoidsendToServer() {

    Intentintent=newIntent(VoterListActivity.this, AddFamilyNuberByVoterList.class);
    intent.putParcelableArrayListExtra("CheckedList", friends);
    startActivity(intent);
    finish();


}


privatevoidgetVoterData() {
    if (Util.isNetworkAvailable(this)) {
        progressBar.setVisibility(View.VISIBLE);
        SendRequestToServer();
    } else {
        progressBar.setVisibility(View.GONE);
        Snackbar.make(listView, R.string.no_connection, Snackbar.LENGTH_SHORT).show();
        return;
    }
}

privatevoidSendRequestToServer() {
    try {
        RegistrationApiapi= ServiceGenerator.createService(RegistrationApi.class);
        retrofit2.Call<VoterDao> call = api.togetVoters(Userid, Token, Appid, Deviceid);
        call.enqueue(newCallback<VoterDao>() {
            @OverridepublicvoidonResponse(Call<VoterDao> call, Response<VoterDao> response) {
                if (response.isSuccessful()) {
                    voterDao = response.body();
                    if (voterDao.getAddData().getStatus().equals(1)) {
                        searchview.setVisible(true);
                        progressBar.setVisibility(View.GONE);
                        friends = (ArrayList<VoterDatum>) voterDao.getAddData().getData();


                        adapter1 = newListView1Adapter(getApplicationContext(), R.layout.list_voter, friends);
                        listView.setAdapter(adapter1);
                        btn_show_me.setVisibility(View.VISIBLE);

                    } else {
                        searchview.setVisible(false);
                        progressBar.setVisibility(View.GONE);
                        Snackbar.make(listView, R.string.no_data_found, Snackbar.LENGTH_SHORT).show();
                    }
                } else {
                    searchview.setVisible(false);
                    progressBar.setVisibility(View.GONE);
                    Snackbar.make(listView, R.string.no_data_found + response.message(), Snackbar.LENGTH_SHORT).show();
                }
            }

            @OverridepublicvoidonFailure(Call<VoterDao> call, Throwable t) {
                try {
                    searchview.setVisible(false);
                    progressBar.setVisibility(View.GONE);
                    Snackbar.make(listView, "" + t.getMessage(), Snackbar.LENGTH_SHORT).show();
                    Log.d("message", "" + t.getMessage());
                    System.out.println("onFAilureExecute" + t.getMessage());
                    if (t != null)
                        t.printStackTrace();
                } catch (Throwable th) {
                    th.printStackTrace();
                }

            }
        });


    } catch (Exception e) {
        e.printStackTrace();
    }
}


privatevoidinitViews() {
    progressBar = findViewById(R.id.reqprogressbar);
    listView = findViewById(R.id.voter_lv);
    btn_show_me = findViewById(R.id.btn_show_me);
}

@OverridepublicbooleanonSupportNavigateUp() {
    startActivity(newIntent(getApplicationContext(), DashboardActivity.class));

    finish();
    overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    returntrue;
}

@OverridepublicvoidonBackPressed() {
    startActivity(newIntent(getApplicationContext(), DashboardActivity.class));
    finish();
    overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}

@OverridepublicbooleanonCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    searchview = menu.findItem(R.id.action_search);
    finalSearchViewsearchViewAndroidActionBar= (SearchView) MenuItemCompat.getActionView(searchview);

    searchViewAndroidActionBar.setOnQueryTextListener(newSearchView.OnQueryTextListener() {
        @OverridepublicbooleanonQueryTextSubmit(String query) {
            returntrue;
        }

        @OverridepublicbooleanonQueryTextChange(String newText) {
            adapter1.getFilter().filter(newText);
            returnfalse;
        }
    });
    ViewcloseButton= searchViewAndroidActionBar.findViewById(android.support.v7.appcompat.R.id.search_close_btn);
    closeButton.setOnClickListener(newView.OnClickListener() {
        @OverridepublicvoidonClick(View v) {
            //handle click

            searchViewAndroidActionBar.setIconified(true);
        }
    });
    returnsuper.onCreateOptionsMenu(menu);
}


@OverrideprotectedvoidattachBaseContext(Context base) {
    super.attachBaseContext(LocalHelper.onAttach(base));
}

privateclassListView1AdapterextendsBaseAdapter {
    ListView1Adapter.ViewHolder holder;
    private Context activity;
    private ArrayList<VoterDatum> Friends;
    private ArrayList<VoterDatum> mList;
    privatefinalStringTAG= ListViewAdapter.class.getSimpleName();
    boolean[] checkedItems;


    publicListView1Adapter(Context applicationContext, int list_voter, ArrayList<VoterDatum> list) {

        this.activity = applicationContext;
        this.Friends = list;
        this.mList = list;
        Log.i(TAG, "init adapter");
        checkedItems = newboolean[mList.size()];
    }

    @OverridepublicintgetCount() {
        return mList.size();
    }

    @Overridepublic Object getItem(int position) {
        return mList.get(position);
    }


    @OverridepubliclonggetItemId(int position) {
        return position;
    }

    @Overridepublic View getView(int position, View convertView, ViewGroup parent) {
        holder = null;
        finalintpos= position;

        // inflate layout from xmlLayoutInflaterinflater= (LayoutInflater) activity
                .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

        // If holder not exist then locate all view from UI file.if (convertView == null) {
            // inflate UI from XML file
            convertView = inflater.inflate(R.layout.list_voter, parent, false);
            // get all UI view
            holder = newListView1Adapter.ViewHolder(convertView);
            // set tag for holder
            convertView.setTag(holder);
        } else {
            // if holder created, get tag from view
            holder = (ListView1Adapter.ViewHolder) convertView.getTag();
        }

        friend = mList.get(position);
        StringnameS= friend.getFirstname() + " " + friend.getLastname();
        StringnamesS= friend.getVoterId();
        Stringlname= friend.getLfname() + " " + friend.getLlastname();
        //set Friend data to viewsStringPhoto= friend.getPhoto();
        if (Photo.isEmpty() || Photo == null) {
            holder.image.setImageResource(R.mipmap.ic_launcher);
        } else {
            Picasso.with(activity).load(Photo).transform(newCircleTransform()).into(holder.image);
        }

        holder.name.setText(nameS);
        holder.lanname.setText(lname);
        holder.voterid_tv.setText(namesS);

        holder.check.setChecked(friend.isChecked());
        holder.check.setTag(friend);
        holder.check.setOnClickListener(newView.OnClickListener() {
            @OverridepublicvoidonClick(View v) {


                CheckBoxcb= (CheckBox) v;
                VoterDatumitemobj= (VoterDatum) cb.getTag();


                if (mList.get(Integer.valueOf(pos)).isChecked()) {
                    cb.setSelected(false);
                    mList.get(Integer.valueOf(pos)).setIsChecked(false);
                    notifyDataSetChanged();


                } else {
                    cb.setSelected(true);
                    mList.get(Integer.valueOf(pos)).setIsChecked(true);
                    notifyDataSetChanged();
                }
            }
        });
        return convertView;
    }

    privateclassViewHolder {
        private ImageView image;
        private TextView name, lanname, voterid_tv;
        private CheckBox check;

        publicViewHolder(View v) {
            image = v.findViewById(R.id.profile_iv);
            name = (TextView) v.findViewById(R.id.name_tv);
            lanname = (TextView) v.findViewById(R.id.desig_tv);
            voterid_tv = (TextView) v.findViewById(R.id.voterid_tv);
            check = (CheckBox) v.findViewById(R.id.chkEnable);
        }
    }

    public Filter getFilter() {
        returnnewFilter() {
            @Overrideprotected FilterResults performFiltering(CharSequence constraint) {
                FilterResultsresults=newFilterResults();

                ArrayList<VoterDatum> filteredResults = null;

                if (constraint.length() == 0) {
                    filteredResults = Friends;
                } else {
                    filteredResults = (ArrayList<VoterDatum>) getFilteredResults(constraint.toString().toLowerCase());
                }


                results.values = filteredResults;

                return results;
            }

            @OverrideprotectedvoidpublishResults(CharSequence charSequence, FilterResults results) {
                mList = (ArrayList<VoterDatum>) results.values;
                notifyDataSetChanged();
            }
        };
    }

    protected List<VoterDatum> getFilteredResults(String s) {
        ArrayList<VoterDatum> results = newArrayList<>();
        for (VoterDatum item : Friends) {
            StringTotalSearch= item.getFirstname() + " " + item.getLastname();
            if (TotalSearch.toLowerCase().contains(s) || item.getVoterId().toLowerCase().contains(s)) {
                results.add(item);
            }

        }
        return results;

    }

    public ArrayList<VoterDatum> getAllData() {
        return mList;
    }
}
}

Model Class

publicclassVoterDatumimplementsParcelable {

 @SerializedName("citizen_id")
@ExposeprivateString citizenId;
privateboolean isChecked;
publicstatic final Parcelable.Creator<VoterDatum> CREATOR = newParcelable.Creator<VoterDatum>() {
    publicVoterDatumcreateFromParcel(Parcel in) {
        returnnewVoterDatum(in);
    }

    publicVoterDatum[] newArray(int size) {
        returnnewVoterDatum[size];
    }
};


publicVoterDatum(Parcelin) {
    this.citizenId = in.readString();

    this.isChecked = in.readByte() != 0;
}

@Overridepublic int describeContents() {
    return0;
}

@OverridepublicvoidwriteToParcel(Parcel dest, int flags) {
    dest.writeString(this.citizenId);

    dest.writeByte((byte) (this.isChecked ? 1 : 0));
}

publicVoterDatum(String citizenId, boolean gender) {
    this.citizenId = citizenId;
    this.isChecked = false; // not selected when create
}


@SerializedName("status")
@ExposeprivateString status;

@SerializedName("firstname")
@ExposeprivateString firstname;
@SerializedName("lastname")

publicbooleanisChecked() {
    return isChecked;
}


publicvoidsetIsChecked(boolean isChecked) {
    this.isChecked = isChecked;
}

publicStringgetStatus() {
    return status;
}

publicvoidsetStatus(String status) {
    this.status = status;
}

publicStringgetCitizenId() {
    return citizenId;
}

publicvoidsetCitizenId(String citizenId) {
    this.citizenId = citizenId;
}

publicStringgetFirstname() {
    return firstname;
}

publicvoidsetFirstname(String firstname) {
    this.firstname = firstname;
}

publicStringgetLastname() {
    return lastname;
}

publicvoidsetLastname(String lastname) {
    this.lastname = lastname;
}

publicStringgetLfname() {
    return lfname;
}

publicvoidsetLfname(String lfname) {
    this.lfname = lfname;
}

}

Get Data From Other Class

publicclassACtivityextendsAppCompatActivityimplementsView.OnClickListener {
StringMvoterid;
GPSTracker gps;
StringToken, Userid, Deviceid, Appid, Language;
Button submit_btn;
ProgressBar progressBar;
AddFamilynumberbyvoterDao addFamilynumberbyvoterDao;
//  ArrayList<VoterDatum> checkedList;List<VoterDatum> checkedList;
LinearLayout container;
VoterDatumModel;
ListView list_item;
String join;
int position;
String userName;
String name;
StringBuilder stringBuilder;
@RequiresApi(api = Build.VERSION_CODES.O)
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_family_nuber_by_voter_list);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle(R.string.add_family_numbers);
    VoterID = getIntent().getStringExtra("voterIDs");
    stringBuilder= newStringBuilder();
     checkedList = newArrayList<VoterDatum>(); // initializing list
    container = (LinearLayout) findViewById(R.id.layout);


    getLocation();

    initViews();
    initListeners();
    getDataFromIntent();
    generateDataToContainerLayout();


}

@RequiresApi(api = Build.VERSION_CODES.O)
@SuppressLint("InflateParams")
privatevoidgenerateDataToContainerLayout() {

    int i = 0;
    if (checkedList.size() == i) { //do nothing
    }
    while (checkedList.size() > i) {
        int count = checkedList.size();
        Model = checkedList.get(i);

        if (Model.isChecked()) {
            Log.i("ListActivity", "here" + checkedList.get(i).getCitizenId());



            stringBuilder.append(","+checkedList.get(i).getCitizenId());
            name=stringBuilder.toString();



            String joinedString = Model.getCitizenId().toString();
            Log.d("ls", "" + name);
            name=name.substring(1);
            Log.d("fs",name);
        }


        i++; // rise i
    }

}

privatevoidgetDataFromIntent() {
    checkedList = getIntent().getParcelableArrayListExtra("CheckedList");

}

Post a Comment for "Android List View Custom Adapter With Checkbox Multiple Selection And Search Listview"