Snackbar sometimes doesn't appear when it replaces another

I am having a weird problem with Snackbars on Android. I am showing error messages via Snackbar + Retry-Action. When retry is clicked and the error is still there (eg no internet), I show the error again. This click on an action in the Snackbar will automatically dismiss the currently displayed one and show the new Snackbar, while the old one, still "disappearing", works as expected.

But sometimes (when I click Retry ~ 30 times) the Snackbar doesn't appear at all after I click the button many times.

I can reproduce it with this simple code:

final View.OnClickListener retryListener = new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        showSnackbar();
    }
};

private void showSnackbar() {
    Snackbar snackbar = Snackbar.make(root, "Error", BaseTransientBottomBar.LENGTH_INDEFINITE)
            .setAction("Retry", retryListener)
            //Callback only for debugging-purposes
            .addCallback(new BaseTransientBottomBar.BaseCallback<Snackbar>() {
                @Override
                public void onShown(Snackbar transientBottomBar) {
                    super.onShown(transientBottomBar);
                    Log.d(TAG, "onShown called");
                }
            });
    snackbar.show();
    Log.d(TAG, "show called");
}

      

When I look at the logcat after having a problem with this code, the last line show called

, and the onShown

-callback was no longer called.

Why is this happening? Should I report this as a problem? Are there any known workarounds?

+3


source to share


1 answer


I have not found a real reason why this is happening and is not a real solution to the problem, but I did find a workaround that works for me:

private Snackbar currentlyShownSnackbar;    

private void showSnackbar() {
    Snackbar snackbar = Snackbar.make(...);
    snackbar.show();
    currentlyShownSnackbar = snackbar;
}

      

By simply saving the link to the currently shown Snackbar, this issue no longer occurs. I don't know why, maybe it is due to garbage collection too early.



Checking the code will tell you that this variable is assigned but never used - this warning can be ignored.

I also added this to my activity to prevent any possible memory leak:

public void onPause() {
    super.onPause();
    this.currentlyShownSnackbar = null;
}

      

+3


source







All Articles