Ali
Ali

Reputation: 187

Null Pointer Exception within DialogFragments, android

Here is a snippet of my code:

public class ChooseNumWorkoutsDialog extends DialogFragment implements OnClickListener {
    Button btnClose, btnFinished;
    NumberPicker np;

    public ChooseNumWorkoutsDialog() {
        // Empty constructor required for DialogFragment
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_numpicker, container);
        getDialog().setTitle("Number of Exercises");
        btnClose = (Button) findViewById(R.id.btnClose);
        btnFinished = (Button) findViewById(R.id.btnFinished);
        np = (NumberPicker) findViewById(R.id.np);
        //np.setMaxValue(20);
        //np.setMinValue(1);
        //np.setWrapSelectorWheel(false);
        //btnClose.setOnClickListener(this);
        //btnFinished.setOnClickListener(this);   
        return view;
    }

The XML file does contain all referenced buttons and numberPickers. When this is run, a Null Pointer exception is found at "np.setMaxValue(20);", the only way I can get it to work is if I comment out all of the commented out parts you see.

Upvotes: 1

Views: 4720

Answers (1)

biegleux
biegleux

Reputation: 13247

Initialize your views in onActivityCreated(). From documentation:

Called when the fragment's activity has been created and this fragment's view hierarchy instantiated. It can be used to do final initialization once these pieces are in place, such as retrieving views or restoring state. It is also useful for fragments that use setRetainInstance(boolean) to retain their instance, as this callback tells the fragment when it is fully associated with the new activity instance. This is called after onCreateView(LayoutInflater, ViewGroup, Bundle) and before onStart().

Than you can call getView().findViewById(R.id.np);

or use np = (NumberPicker) view.findViewById(R.id.np); in onCreateView(), notice the "view."

Upvotes: 4

Related Questions