2

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!

azizbekian
  • 60,783
  • 13
  • 169
  • 249
DCoutts
  • 124
  • 2
  • 7

1 Answers1

1

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());
    }

azizbekian
  • 60,783
  • 13
  • 169
  • 249
  • Thanks, I didn't know about the create method! However, it is only supported on api 21 upwards and I need to support 17 upwards. Do you know if there's a way to do this below api level 21? – DCoutts Jun 12 '17 at 13:39
  • You can take another approach, handle clicks inside BasicDialog, so you will subscribe in Dialog's onCreate() – Tuby Jun 12 '17 at 13:43
  • @DCoutts, for APIs lower 21 you have to perform `basicDialog.show()` and after that perform `basicDialog.button1Clicks()`. – azizbekian Jun 12 '17 at 13:44