Question

I have a custom preference, TimePreference, which extends DialogPreference. It has a custom dialog resource, which looks like this

Three buttons with their IDs

The source is

@Override
protected void onBindDialogView(View v){
    super.onBindDialogView(v);

    v.findViewById(R.id.butCancel).setOnClickListener(onClickL);
    v.findViewById(R.id.butNow).setOnClickListener(onClickL);
    v.findViewById(R.id.butOK).setOnClickListener(onClickL);
    //....
}
//...
private final View.OnClickListener onClickL = new View.OnClickListener(){
    @Override
    public void onClick(View v) {
        Log.d(lTag, v + " clicked");
        switch (v.getId()) {
            case R.id.butOK: saveToSP(false);break;
            case R.id.butNow: saveToSP(true);
        }

        try {
            getDialog().dismiss(); //may throw null pointer
        } catch (Exception e) { Log.w(lTag, "Exc @onClickL", e); }
    }
};
//...

I found a bug where, if you clicked the same preference really fast twice (at the preference screen) two dialogs would open. You could close the first one but, when you would try to close the second, the app would crash. It was a NullPointerException, so I enclosed it in a try-catch block. Now, the exception is caught, but the buttons do not close the dialog. Notice that, by clicking back, it does close.

How can I close the second dialog (possibly by simulating the behaviour of the back button?) ? Note, I want the API level below 10.

Was it helpful?

Solution

Okay, I found a soultion. I have a static boolean, which shows if there is an open dialog.

private static boolean isAnyDialogOpen = false;

On dialog bind, I set it to true, And after I close the dialog, I set it to false. Turned out that even this was problematic, but the solution was easier

@Override
protected void onClick() {
    if (isAnyDialogOpen)
        Log.i(lTag, "there is a dialog already");
    else {
        isAnyDialogOpen = true;
        super.onClick();
    }
}
@Override
public void onDismiss(DialogInterface dialog) {
    Log.d(lTag, "dismiss, dialog= "+dialog);

    isAnyDialogOpen = false;
    if (dialog != null) super.onDismiss(dialog);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top