简体   繁体   中英

Multiple checkbox can not be checked

I'm trying to check the checkbox per item but the app keeps on crashing.

This is my NewIngredients:

public class NewIngredients extends AppCompatActivity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate (savedInstanceState);
       setContentView (R.layout.activity_new_ingredients);

       readCSV ();
   } 

   public void readCSV(){
       List<IngredientsHolder> data = new ArrayList<> ();
       try {
           String sCurrentline = null;
           BufferedReader br = new BufferedReader(new FileReader ("/sdcard/TABLE_BF.csv"));
           sCurrentline = br.readLine ();
           while ((sCurrentline = br.readLine()) != null) {
               String[] arr = sCurrentline.split(",");
               IngredientsHolder ingredient = new IngredientsHolder(arr[0], arr[1], arr[2]);
               data.add(ingredient);
           }
           br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Map<String, List<IngredientsHolder>> ingredientsByName = data.stream().collect(Collectors.groupingBy(IngredientsHolder::getName));

        List<IngredientsHolder> main = new ArrayList<>();
        List<IngredientsHolder> other = new ArrayList<>();

        //Sort on `admin` in descending order
        Comparator<IngredientsHolder> comparator = Comparator.comparing(IngredientsHolder:: getAdmin, (i1, i2) -> {
            if (i2 > i1) {
                return -1;
            } else if (i2 < i1) {
                return 1;
            }
            return 0;
        });

        //Go through each list (ingredient) and find the one with max `admin` value
        //and add it to the `main` list then add the rest to `other`
        ingredientsByName.forEach( (k, group) -> {
            IngredientsHolder max = group.stream().max(comparator).get();
            if (max.getAdmin() == 0) {
                max = group.get(0);
            }if(max.getAdmin () > 0){
                //group.forEach(System.out::println);
                int value = max.getAdmin ();

                List<IngredientsHolder> filtered = (group.stream()
                             .filter(mc -> mc.getAdmin() == value)
                             .collect(Collectors.toList()));
                //filtered.forEach(mc -> System.out.println (mc.toString ()));
            }

            main.add(max);
            group.remove(max);
            other.addAll(group);
            System.out.println (other.size ());
        });

        List<IngredientsHolder> newMain = main.stream().distinct().collect(Collectors.toList());
        ListView lv = (ListView) findViewById(R.id.list);
        lv.setAdapter(new CustomAdapter(NewIngredients.this,newMain));
    }
}

This is my CustomAdapter:

public class CustomAdapter extends ArrayAdapter {
    private LayoutInflater mInflater;
    List<IngredientsHolder> ingredientsList;

    public CustomAdapter(Context context, List<IngredientsHolder> list){
        super(context,0,list);
        ingredientsList = list;
        mInflater = LayoutInflater.from(context);
    }

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

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.custom_ni,parent,false);
            // inflate custom layout called row
            holder = new ViewHolder();
            holder.tv =(TextView ) convertView.findViewById(R.id.textview);

            // initialize textview
            convertView.setTag(holder);
        }
        else {
            holder = (ViewHolder)convertView.getTag();
        }
        IngredientsHolder in = (IngredientsHolder)ingredientsList.get(position);
        holder.tv.setText(in.subName);
        // set the name to the text;

        return convertView;

    }

    static class ViewHolder {
        TextView tv;
    }
}

This is my IngredientsHolder:

public class IngredientsHolder {
    String name;
    String subName;
    int admin;

    public IngredientsHolder(String name, String subName, String admin) {
        this.name = name;
        this.subName = subName;
        this.admin = Integer.valueOf(admin);
    }

    public String getName() {
        return name;
    }

    public String toString() {
        return subName;
    }

    public int getAdmin() {
        return admin;
    }
}

This is my custom_ni.xml file:

<CheckBox
    android:id="@+id/checkbox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentEnd="true"
    android:layout_centerVertical="true"
    android:layout_marginEnd="7dp"
    android:onClick="clickHandler"></CheckBox>

<TextView
    android:id="@+id/textview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_marginLeft="13dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="9dp"
    android:layout_toLeftOf="@id/checkbox"
    android:text="TEST"
    android:textColor="#000"
    android:textSize="18sp" />

</RelativeLayout>

This is the stacktrace:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.kenneth.thisforthat, PID: 27999
              java.lang.IllegalStateException: Could not find method clickHandler(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatCheckBox with id 'checkbox'
                  at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:423)
                  at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:380)
                  at android.view.View.performClick(View.java:6312)
                  at android.widget.CompoundButton.performClick(CompoundButton.java:134)
                  at android.view.View$PerformClick.run(View.java:24802)
                  at android.os.Handler.handleCallback(Handler.java:790)
                  at android.os.Handler.dispatchMessage(Handler.java:99)
                  at android.os.Looper.loop(Looper.java:169)
                  at android.app.ActivityThread.main(ActivityThread.java:6521)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

I tried some tutorials and some suggestions but i can't seem to implement anything right.

What i really want to do is check multiple items and store those checked items into arraylist and those also store those unchecked items in another arraylist.

clickHandler,源代码中缺少Method。

Checkbox with id checkbox has a click handler with name clickHandler but it is no implemented in the java class.

Either remove

android:onClick="clickHandler"

or Add the clickhandler method to the java class.

public void clickHandler(View view) {

}

You should keep one flag in your man ArrayList to set selected and unselected Checkbox on the basis of flag value .

So you no need to make two separate lists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM