samedi 31 décembre 2016

Using context without any static reference

I am trying to access application resources, (string resources to be specific) from a Singleton class. Being Singleton, this class cannot hold any reference to Context objects (to prevent memory leak). While I was looking for other implementations on the net, I came across this two implementation:

  1. Create a static context in Application class and use it across the app.
  2. Pass context as a parameter to the method that requires it.

I don't want to use the fist one as it also uses a static reference to Context object. I understand that it's ok to have it statically in the Application class of android, but still it looks like a hack.

The second implementation is useless since i don't have any instance of context which I can pass to the someOtherMethod of the singleton.

So I came up with following implementation where I make my Singleton abstract to override its context requiring methods (for ex. getString(int resId) in the code below) when I initialize the singleton instance.

I am curious to know if this can lead to any memory leaks now?

Where am I confused with this approach:

--> The reference to context in the Overridden getString is final. I am not sure if that can cause a memory leak or not.

    public abstract class SingletonClass{

    .
    .
    .

    private static SingletonClass sInstance;

    private SingletonClass(Context paramContext) {
        // constructor code
    }

    public static SingletonClass getInstance(final Context context) {
        if (sInstance == null) {
            sInstance = new SingletonClass(context){
                @Override
                public String getString(int resId) {
                    return context.getString(resId);
                }
            };
        }
        return sInstance;
    }

    public abstract String getString(int resId);

    .
    .
    .

    private void someOtherMethod(){
        //uses above getString()
    }

    }

Aucun commentaire:

Enregistrer un commentaire