Search code examples
javaandroidandroid-fragmentsandroid-dialogfragmentandroid-configchanges

Dismiss dialogue after configuration is changed


I'm currently writing on a Bluetooth application only allowing the user to work with it in the portait mode. However, there are some other reasons causing confguration changes forcing me to show the user that the Bluetooth connection has been lost.

While connecting to a device I show a dialogue prompting a password. If a configuration change occurs while this dialogue is visible I want to dismiss it. Therefore I call a helper method in onSaveInstanceState, onDestroy as well as onCreate (if the saved instance state is not null).

@Override
public void onCreate(Bundle savedInstanceState)
{
    if (savedInstanceState != null)
    {
        this.tryDismiss();
    }
    super.onCreate(savedInstanceState);
}

@Override
public void onSaveInstanceState(Bundle outState)
{
    System.out.println("Saving instance state!");
    this.tryDismiss();

    super.onSaveInstanceState(outState);
}

@Override
public void onDestroy()
{
    System.out.println("Destroying dialogue!");
    this.tryDismiss();

    super.onDestroy();
}

public void tryDismiss()
{
    try
    {
        System.out.println("DIE BART, DIE!");
        this.dismissAllowingStateLoss();
    }
    catch (Exception closingException)
    {
    }
}

However, the dialogue is still displayed to the user. I have read a similar questions, but couldn't figure out a solution to this issue.

I appreciate any help. Thanks in advance!


Solution

  • Using a strong reference in the activity displaying the dialogue and invoking the dismiss() method in the activitie's onSaveInstanceStatemethod fixed this issue for me. I know, it's not the most optimal solution, but it works.

    @Override
    protected void onSaveInstanceState(Bundle persistantState)
    {
        if (this.connectionPasswordDialogue != null)
        {
            this.connectionPasswordDialogue.dismiss();
        }
    }
    

    With strong reference I mean a private attribute used internally by the activity:

    private DialogueUserModePassword connectionPasswordDialogue;