DCoutts DCoutts -4 years ago 42
Android Question

NPE when subscribing to dialog button clicks

I have created a custom dialog in my app, and I want to add button click observables like so:

public class BasicDialog extends android.app.Dialog {

@BindView(R.id.button1)
TextView button1;
@BindView(R.id.button2)
TextView button2;

public BasicDialog(Context context) {
super(context);
}

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

...

ButterKnife.bind(this);
}

public Observable<Object> button1Clicks() {
return RxView.clicks(button1);
}

public Observable<Object> button2Clicks() {
return RxView.clicks(button2);
}
}


I then create my dialog and subscribe to button 1 clicks in my activity like this:

@Override
protected void onCreate(Bundle savedInstanceState) {

...

BasicDialog basicDialog = new BasicDialog(this);

basicDialog.button1Clicks()
.subscribe(__ -> doStuff());
}


This results in a null pointer exception, as
button1
is null at the point of subscription.

I know a possible fix to this would be to use a
PublishSubject
in the dialog instead of trying to subscribe directly to the button click observable, but this seems like a very inelegant solution.

Thanks in advance for any suggestions!

Answer Source

The problem is, that you are subscribing to button click too early.


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        ...

        BasicDialog basicDialog = new BasicDialog(this);
        // `basicDialog` hasn't yet been created, it has no view hierarchy inflated yet

        // Force create the dialog
        basicDialog.create();

        // Now you have your dialog created
        basicDialog.button1Clicks()
                .subscribe(__ -> doStuff());
    }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download