简体   繁体   中英

how to make a snackbar accessible from any activity in android?

i have declared below snackbar in main activits and tried to call from another java class .but it crashed my app with below errors . how can i make a snackbar accessible from any activity or any non activity java classes.

i am calling snackbar declared in an activity from another java simple class as below

MainActivity main=new MainActivity();
showSnackbar("EASY BOSE WE ARE ONLINE ");

But it returns this error and crashed my app

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference

public void showSnackbar(String message){
     View rootView = findViewById(android.R.id.content);
     if(rootView != null) {
         Snackbar.make(rootView, message, Snackbar.LENGTH_LONG).show();
     }
 }

You never call new on any Activity. That will not correctly initialize it. The only way to correctly initialize an Activity is for the framework to do it, which happens when startActivity is called with the proper Intent.

You wouldn't make a Snackbar from on Activity accessible in any other Activity. Because that Snackbar is only visible when the Activity is in the foreground. Those other Activities should make their own if they want to show one.

If you want another class to change the Snackbar of an Activity, you pass that Snackbar in as a parameter to that class, either in the constructor or in the method you call. Please note that even if you do save a snackbar from the main activity in some other class and access it later, changing anything in it will have no effect on Snackbars in other activities. Please also not that you should NEVER save a view in a static variable or try to make it persist longer than the Activity its a part of, as doing so will cause a massive memory leak.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM