0

Is it ok to use this pattern in android and then use App.context whenever application context is required?
I want to access getString(id) in enum class, so thinking of this solution.

public class App extends Application 
    public static  Context context;

    public App() {
        this.context = this;    
    }
}
  • Well it wouldn't hurt but variable declare in you App class have scope equal to your application lifetime means as long as App is running you can access these variable any time anywhere , so no need to declare it static just make a getContext() function inside it and return Context variable and call this function whenever by creating instance of this class – Sanjeev Jul 30 '15 at 02:28
  • Prefer singleton over application class.http://stackoverflow.com/questions/3826905/singletons-vs-application-context-in-android. No need for static modifier. – Raghunandan Jul 30 '15 at 03:06
  • @Raghunandan he can't make it a traditional singleton (private constructor, public static method to retrieve the instance). It is a subclass of `Application`, so it must have a public no-arg constructor. – Karakuri Jul 30 '15 at 04:13
  • @Karakuri i meant to say instead of application class have your own singleton class. I think you misunderstood my quote – Raghunandan Jul 30 '15 at 05:19

1 Answers1

1

The rule is never to hold a strong reference to a Context beyond its normal lifetime. Android manages the Application instance when your app is in use--there will always be one and only one for as long as Android keeps your app running. In short, the Application context is the only one you can hold a reference to without worrying it will leak.

However, I think it's better to make the assignment in onCreate() instead of in the public constructor. With few exceptions, for components managed by Android, onCreate() should be the place you start running your own code.

@Override
public void onCreate() {
    super.onCreate();
    appContext = this;
}
Karakuri
  • 38,365
  • 12
  • 84
  • 104