mercredi 8 mai 2019

How to fix 'Attempt to invoke virtual method on a null object reference' error in java [duplicate]

This question already has an answer here:

I am creating a To-Do-List Application where the user gains points every time the using tick the Check Boxes but I keep getting the NullPointerException everytime I run it.

I have used this line of code to adapt the checkboxes from the Layout "inner_checkview.xml"

Log.d(TAG, "populateCheckView: Display Data in the CheckboxView ");

    Cursor data = DTH.getTasks();
    ArrayList<String>TaskList = new ArrayList<>();
    while(data.moveToNext()){
        TaskList.add(data.getString(1));
    }
    ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,  TaskList);
    tListView.setAdapter(adapter);

    tListView.setAdapter(new ArrayAdapter<>(this, R.layout.listrow, R.id.textView2, TaskList));

    tListView.setAdapter(new ArrayAdapter<>(this, R.layout.inner_checkview, R.id.checkBox1, TaskList));


    mCheckBox = findViewById(R.id.checkBox1); // This is where the problem is 

    mCheckBox.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mCheckBox.isChecked()){
                int points = 10;
                AddPoints(points);

            }else{
                int points = 10;
                SubtractPoints(points);

            }
        }
    });

When I run the program, visit the page and click the check boxes it should and ten point and display the points on the interface.

But instead the program Crashes and shows this error on the LogCat

java.lang.RuntimeException: Unable to resume activity {TDCollections.premix/TDCollections.premix.CheckBoxActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CheckBox.setOnClickListener(android.view.View$OnClickListener)' on a null object reference




Aucun commentaire:

Enregistrer un commentaire