To avoid a memory leak I wrote the following method that will be used in activities and mainly in fragments (using inheritance). That method is supposed to allow me to never directly refer to the activity by calling
//this or getActivity()
The method is:
private WeakReference<BaseActivity> activityWeakReference = null;
public BaseActivity getActivityFromWeakReference(){
activityWeakReference = activityWeakReference == null ?
new WeakReference<BaseActivity>((BaseActivity)getActivity()) :
activityWeakReference;
return activityWeakReference.get();
}
Is calling this method getActivityFromWeakReference() instead of getActivity() safe according to memory leak threat?
If it is not safe to do so, should I return the activityWeakReference and call its get() method instead, to make it safe?
I have been using it in multiple fragments and I haven't had any problem so far. I ask the question because I read this (here):
As long as the lifetime of the helper is within the lifetime of the
Activity, then there's no need to use aWeakReference. If the helper can live longer than theActivity, then you should use aWeakReferenceto avoid retaining theActivityin your object graph when the system destroys it.
So far, I haven't faced a case where a referred element outlived the activity. Please guys if you find an error or a possible one just write it in the comments.