Search code examples
androidandroid-studioandroid-layoutfindviewbyidandroid-snackbar

Snackbar not showing, the app crashes every time I open it


I tried to resolve this error but I wasn't successful with it. When is open the application the app crashes and stops instantly. Is there something am not doing right?

    private void popupSnackBarForCompleteUpdate() {
        Snackbar.make(findViewById(android.R.id.content), "New app is ready!", Snackbar.LENGTH_INDEFINITE)

        .setAction("Install", view -> {
            if (appUpdateManager != null) {
                appUpdateManager.completeUpdate();
            }
        })
        .setActionTextColor(getResources().getColor(R.color.installColor))
        .show();
    }

Throws the following error:

java.lang.IllegalArgumentException: No suitable parent found from the given view. Please provide a valid view.
        at com.google.android.material.snackbar.Snackbar.make(Snackbar.java:158)

I had the below code before switching to android.R.id.content

    private void popupSnackBarForCompleteUpdate() {
        Snackbar snackbar =
                Snackbar.make((CoordinatorLayout) findViewById(R.id.snackbar_layout), "New app is ready!", Snackbar.LENGTH_INDEFINITE);

        snackbar.setAction("Install", view -> {
            if (appUpdateManager != null) {
                appUpdateManager.completeUpdate();
            }
        });
        snackbar.setActionTextColor(getResources().getColor(R.color.installColor));
        snackbar.show();
    }

Solution

  • if you want to fetch the rootview for your activity then you should use :- findViewById(android.R.id.content).getRootView(). (You are missing getRootView() here).

    Or else you can also use requireView().rootView and it will return you root view of your fragment and have a look at this answer as well to get rootview from your activity.