0

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.

Lev M.
  • 6,088
  • 1
  • 10
  • 23
  • @Apurva Thanks, but can you please help me out in solving above my confusion, plz. –  Mar 15 '15 at 11:11

1 Answers1

0

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

nasch
  • 5,330
  • 6
  • 31
  • 52
  • thanks, I really appreciate for the suggestions. BTW, I'm following the same way as you've mentioned in answer. But my concerns is regarding having static instance to access it in nob activity classe . Is this correct? Or I should remove static instance from Application. –  Mar 16 '15 at 09:47
  • I would remove the static instance. I doubt it would cause a problem but there's no need for it. – nasch Mar 16 '15 at 15:11
  • So, you're saying for the non activity classes, I'll have to pass the context by calling it's constructor, not by static way? –  Mar 22 '15 at 07:29
  • If you mean how to access the Application from outside an activity class, yes you would have to pass something in. – nasch Mar 22 '15 at 20:07