Search code examples
androidweak-references

Android WeakReference


I have an activity where i have to trigger from place to place a custom pop-up dialog which is also a singleton

From my activity i open the pop-up :

  ScheduleDialog.getInstance().refreshContent(new WeakReference<Context>(this), new WeakReference<ScheduleDialog.interface>(this));

What is best ? 1) create 2 local references ( in ScheduleDialog ) like :

   Context mContext = nContext.get();

2) keep both like weak reference and only when i need them use :

nContext.get();

This is related about leaks error/warnings

Thanks


Solution

  • If I see your code you create strong reference again after get weak reference value in Context nContext variable. So need to follow below process if you want to implement weak reference concept :-

    define global class variable :-

    private final WeakReference< Context > nContext;
    

    set value in global variable through passing from another area

    nContext = new WeakReference<Context>(nContext);
    

    and then

    if (nContext.get() != null) 
        // code
    }
    

    https://medium.com/google-developer-experts/weakreference-in-android-dd1e66b9be9d