0

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

1
  • You did not explain why you are using WeakReference for context (if in fact you can use Application context) and also show the ScheduleDialog code (otherwise we do not know if your code is leaky). Commented Feb 8, 2018 at 12:33

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

5 Comments

I think you mean member variable cuz we don't have global variable in Java.
so you are pointing on the second option but with a little update : ScheduleDialog.getInstance().refreshContent(this,this) with the help of your article. Right ?
@user863873 honestly I don't see the point of using WeakReference not unless your dialog can outlive your view like for example how Thread does (that's the only case you worry for leak).
i see your point. May be is a dummy question but : what if i have multiple activities and each one has recyclerview + adapter. If i use weakreference in each adapter if there will be memory problem ... only the adapter(s) will be GC. Or this is not possible because adapter is a member variable in activity and if memory problem also the activity will be GC ?
@user863873 if your activity is destroyed your Adapter and RecyclerView will also be Garbage collected (since your activity is the only the one holding the reference to them not unless a static reference is holding them or a background Thread itself). You could experiment this using LeakCanary.
0

You have to keep them as WeakReferences, otherwise the Garbage Collector will see there are strong references to the object and won't collect them, leading to the leak you mentioned.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.