1

I am developing an Android application and maintaining Global Variables in an Application Class MyAppData. Now in order to use those global variables, I am creating the MyAppData object in my Activity as follows:

MyAppData mad;
mad = (MyAppData)getApplication();

As my activity have a custom Listview, I am using BaseAdapter to populate the LstView. Now i need to use the global variables in my BaseAdapter class. The following code doesnt allowing me to create an object of MyAppData class :

public class AlbumList_Adapter extends BaseAdapter{
Context context;
MyAppData mad;

      public AlbumList_Adapter(Context context){
      this.context = context
      mad = (MyAppData)getApplication();
      }
}

Even I had tried mad = (MyAppData)context; but no Luck. I dont know where I have mistaken.

Dileep Perla
  • 1,865
  • 7
  • 33
  • 54
  • http://stackoverflow.com/questions/3826905/singletons-vs-application-context-in-android/3827166#3827166 – Samir Mangroliya Jul 04 '12 at 11:19
  • What kind of global variables are there? This is probably a bad design. – Egor Jul 04 '12 at 11:24
  • And additionally with your code you're not *creating* object, you're getting object. – pawelzieba Jul 04 '12 at 11:29
  • Sorry for the late reply guys. Singleton and Application class both have their advantages and disadvantages. I preferred Application class because whenever I start my application, im getting startup data from shared preferences through Appication class as the appication class runs first when an app is opened. – Dileep Perla Jul 04 '12 at 16:50

1 Answers1

9

You can have:

class MyApplication extends Application {

 private static MyApplication mInstance;

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

public static MyApplication getInstance() { return mInstance; }

}

Then you can use MyApplication.getInstance() throughout your code.

Alexander Kulyakhtin
  • 47,782
  • 38
  • 107
  • 158