lundi 20 juillet 2015

Attempt to invoke virtual method 'void android.widget.CheckBox.setSelected(boolean)' on a null object reference

I have a fragment PrearrivalPlan that belongs to an activity MainActivity that gets called after a user selects the "New Checklist" button on the main menu of my application. In PrearrivalPlan's OnCreateView() method, it adds all the checkboxes on it's screen to a list checkboxList using the fillCheckboxList() method. It then receives data from a local SQLite database to populate those checkboxes to the state that they were before, using the restoreCheckBoxStates() method. However, when it gets to this line:

  checkboxList.get(i).setSelected(false);

The application crashes and throws the error: Attempt to invoke virtual method 'void android.widget.CheckBox.setSelected(boolean)' on a null object reference

The odd thing is, I know that checkboxList is filled with (12) CheckBox objects because I debugged the application and saw so. So why is it not able to call that method on my checkbox? What is the null object reference? It's worth mentioning that the Cursor's count is also 12 so it shouldn't be trying to access a checkbox that is out of range either.

public class PrearrivalPlan extends Fragment {

private static ArrayList<CheckBox> checkboxList = new ArrayList<CheckBox>();

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    final View rootView = inflater.inflate(R.layout.layout_prearrival_plan, container, false);

    fillCheckboxList(rootView, numberOfCheckBoxes);
    restoreCheckBoxStates(rootView);

    return rootView;
}


private void restoreCheckBoxStates(View view) {
    DatabaseOperations dbo = new DatabaseOperations(view.getContext());
    Cursor CR = dbo.getPrearrivalInformation(dbo);
    CR.moveToFirst();


    for (int i = 0; i < checkboxList.size(); i++) {
        if (CR.getInt(0) == 0) {
            checkboxList.get(i).setSelected(false);
        } else  {
            checkboxList.get(i).setSelected(true);
        }
    }

}

private void fillCheckboxList(View view, int numberOfCheckBoxes) {
    for (int i = 0; i < numberOfCheckBoxes; i++) {
        int resourceId = getResources().getIdentifier("prearrival_" + i, "id", getActivity().getPackageName());
        CheckBox cb = (CheckBox) view.findViewById(resourceId);
        checkboxList.add(cb);
    }
}

Aucun commentaire:

Enregistrer un commentaire