mercredi 25 janvier 2023

Android: When checkbox is clicked, create chip

My app has a fragment where the user has to select some dances from a list of checkboxes. Let's use "Argentine Tango" as an example. When I select a checkbox, I get the exception "java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.chip.ChipGroup.addView(android.view.View)' on a null object reference"

When I checked on the checkbox, I wanted a chip writing "Argentine Tango" to appear

private CheckBox mTango; private ChipGroup mChipgroup; private ArrayList mChipList = new ArrayList<>();

Then, inside "OnCreateView"

mTango = view.findViewById(R.id.argtango); mTango.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if (compoundButton != null) { mChipList.add("Argentine Tango"); displayChipData(mChipList); } else { Toast.makeText(getContext(), "There was an error, try again", Toast.LENGTH_SHORT ); } } });

My displayChipData method:

`private void displayChipData(ArrayList mChipList) { for (String s: mChipList) { Chip chip = (Chip) this.getLayoutInflater().inflate(R.layout.single_chip, null, false); chip.setText(s); mChipgroup.addView(chip); }

}`

When I run the app and check the "Argentine Tango" checkbox, the app closes and I get the following exception

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.chip.ChipGroup.addView(android.view.View)' on a null object reference

Any ideas on how I could fix this? Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire