I'm developing an Android app and I’m trying to call findViewById or startActivity from inside a static helper class I created. I keep getting the error about non-static methods. I know these are methods of the Activity class, but how do I get a reference to the current activity inside my static utility without causing memory leaks? I'm stuck and can't move my navigation logic.
3 answers
In Android, methods like startActivity require a Context. Since your utility method is static, it doesn't have a Context. The standard way to solve this is to pass the Context as a parameter to your static method: public static void navigate(Context context) { ... context.startActivity(intent); }. To avoid memory leaks, never store this Context in a static variable. Only use it locally within the method and then let it go. This allows you to keep your helper methods static while still accessing the non-static features of the Android Framework safely.
Is it better to pass the 'Activity' or the 'ApplicationContext'? I’ve heard ApplicationContext is safer for preventing leaks in static contexts.
If you have a lot of these calls, consider making your Utility class a non-static Singleton that you initialize with the Application Context once.
A Singleton is a great middle ground. It gives you the "global" access of a static method but the flexibility of an instance method.
It depends on what you're doing. For startActivity, an Activity context is preferred because it maintains the back stack correctly. For something like a Toast or getting a system service, ApplicationContext is safer. Just remember: as long as you aren't saving the context to a static field, you won't leak the Activity, even if you pass the full Activity reference into the method.