With this question the main concern is what could be best approach. In my android app an Application class is subclassed mainly for two reasons,
1), Maintaining the global state across the app,
2), Ability to initialise and use SharedPreferences in non-activity classes.
The code is somewhat like this,
public class GlobalApp extends Application {
private static GlobalApp instance;
private Bitmap bitmap;
@Override
public void on create(){
super.on create();
instance = this;
}
public static GlobalApp getInstance() {
return instance;
}
public void setBitmap(Bitmap b) {
this.bitmap = b;
}
}
As you can see, to have access of application context in non-activity class, it has been taken as the static whereas other fields are simply instance variables, in which we are storing Bitmaps, will it cause the memory leak ? And above approach is best? Or it can be made even better than this?
Please help.
I don't see anything there that could cause a memory leak. However, you needn't store and retrieve the instance like that, you can just do this:
GlobalApp app = ((GlobalApp)this.getApplication());
Just make sure to add the application class name to the manifest. Keep in mind also that just because there isn't a memory leak doesn't mean there isn't a memory problem. If you hold on to too much memory in that Application object, your app could crash with an OutOfMemoryError. Depending on your exact needs you may need to use weak references to avoid that. More info about using the Application class: Using the Android Application class to persist data