After reading the the Avoiding memory leaks article by @RomainGuy I realized that my current Android application is plagued with the mistake of passing the application's main activity around. So whenever I, can I simply replace that activity parameter with Activity.getApplicationContext().
But there are certain classes in my application that still need to run methods that can only be members of the applications main activity.
Thus I was thinking of possibly using the Command Pattern to workaround this limitation.
The problem is that, if we look at that example:
public class SomeCommandExecuableOnlyByActivity implements Command
{
public void execute(Object data)
{
doIt( ((MyActivity)data).getWindow() );
}
}
I am running again into the dead end of needing the pass around the activity (this time disguised as Object
data).
How do I get out of this "chicken & the egg" situation?
Is there a better way to approach this problem?
Application
when you specifically and precisely know why you are using it. It is not a blanket replacement forActivity
, particularly for UI work. – ArgillaceousMainActivity.staticPrefs
. Is this considered "Putting it in static data members"? – MatherSharedPreferences
is an interface, and I do not readily see where the concrete implementation is, I don't know. If theSharedPreferences
does hold onto aContext
-- and it might -- then you would either need to useApplication
or avoid the static data member. I would expectApplication
to work fine with aSharedPreferences
. – ArgillaceousSharedPreferences
doesn't hold on to anyContext
. In fact, there is only one instance ofSharedPreferences
for each preferences-file within a given process. So there's no problem putting this in a static variable. – ContinuatorContext
, which would immediately leak if it's strongly reachable, in this case until the class is removed from memory. I have never, ever, heard a good reason why an object would have to be kept in a static reference. If your code requires you to do that, I would question the overall design of your code. (...) – Essayistic