0

I'm using the pattern of extending Application class to save my global variables (https://stackoverflow.com/a/708317/1709805). From my Android Components (Activity, Fragment, Service, ecc) i access them using ((MyApp) getApplicaction()), but in my project i have a lot of helper classes where i can't (obviously) use that method. To solve this problem i have decalred a static method which returns the Application. This is the code:

public class MyApp extends Application{

  private static MyApp app;

  @Override
  public void onCreate(){
      super.onCreate();
      app = this;
  }

  public static MyApp getApp() {
      return app;
  }
}

is it a good pattern? Any suggestion to achieve my purpose in a better way? Thank you

Community
  • 1
  • 1
user1709805
  • 2,028
  • 3
  • 19
  • 26

1 Answers1

3

Its a Bad practice.

Just use, MyApp app = (MyApp)getApplicationContext(); in entire application.

Make sure you have declared MyApp in <application> tag of AndroidManifest.xml file

What you have to do is, When you want to access MyApp app object in other Non Android Component class, then pass MyApp app as an argument of Constructor or Method to non Android Component classes (Helper, Handler or Other Java class) from Android Component Class (Activity, Fragment, Service, etc).

user370305
  • 108,599
  • 23
  • 164
  • 151
  • ok.. i have evaluated this possibility. it's a solution which works for sure.. but i'm very lazy so I would prefer not pass a reference of MyApp to each class or method ;). Why my approach is so wrong? – user1709805 Feb 21 '13 at 10:06