Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Dialog Fragment Crashes when Setter Method is Called

I have a CustomDialogFragment like this

public class CustomDialogFragment extends DialogFragment {

    private LinearLayout containerView;


    public static CustomDialogFragment newInstance() {
        CustomDialogFragment fragment = new EDActionSheet();
        return fragment;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        final Dialog dialog = new Dialog(getActivity());
        dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        //MARK - containerView
        LinearLayout.LayoutParams containerViewLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

        containerView = new LinearLayout(dialog.getContext());
        containerView.setLayoutParams(containerViewLayoutParams);
        containerView.setOrientation(LinearLayout.VERTICAL);
        dialog.setContentView(containerView);
        DisplayMetrics displaymetrics = new DisplayMetrics();
        dialog.getWindow().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);

        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = (int) (displaymetrics.widthPixels * 0.95);
        params.gravity = Gravity.BOTTOM;
        dialog.getWindow().setAttributes(params);

        return dialog;
}

public void setColor(int color) {
      containerView.setBackgroundColor(color);
}

And from outside where I call the DialogFragment.

    CustomDialogFragment fragment = CustomDialogFragment.newInstance();
    fragment.setColor(ContextCompat.getColor(this, Color.BLUE));
    fragment.show(getFragmentManager(), "Dialog");

I got the crash saying

 testapp.android.testapp E/AndroidRuntime: FATAL EXCEPTION: main
         Process: id.testapp.android.testapp, PID: 5749
         java.lang.NullPointerException: Attempt to invoke virtual method 'void
 id.testapp.android.testapp.controls.CustomDialogFragment.setColor(int)'
 on a null object reference
         at 
id.testapp.android.testapp.controls.CustomDialogFragment.setColor(CustomDialogFragment.java:234)

Any thoughts?

like image 797
JayVDiyk Avatar asked Jan 01 '16 04:01

JayVDiyk


1 Answers

your containerView reference isn't initialized yet. Look at how onCreateDialog() has to be called before it is initialized.

You will need to refactor in one of a few ways. The easiest would probably to just have the setColor method just store a variable as to what 'containerView' should set its background too when it IS initialized.

like image 78
mawalker Avatar answered Oct 21 '22 08:10

mawalker