0

I have a singleton class, and i want to pass a weak reference of an activity to it.

The activity is implementing an interface, and all of the activities will be implementing this interface, so i want to pass interface type to singleton class.

This is what i am doing.

Interface

public interface IAnalytics {

    String getAnalyticViewName();
}

Singleton Class

  public static AnalyticsWrapper getInstance(WeakReference<IAnalytics> iAnalytics) {

        IAnalytics activityObject = iAnalytics.get();
        activityName = activityObject.getAnalyticViewName();
}

MainActivity

    public  class MainActivity extends AppCompatActivity implements IAnalytics{

      private WeakReference<MainActivity> weakReference;

     protected void onCreate(Bundle savedInstanceState) {
           AnalyticsWrapper analyticsWrapper= AnalyticsWrapper.getInstance(weakReference);
    }
}

This issue is that when i am passing this to AnalyticsWrapper,it saying to change the getInstance() type to weakReference<MainActivity>

dev90
  • 7,187
  • 15
  • 80
  • 153
  • 1
    just change `WeakReference` to `WeakReference extends IAnalytics>` – Lino Apr 30 '18 at 07:57
  • Thanks @Lino, the error is gone, can you please tell me whats the difference between the 2 approach – dev90 Apr 30 '18 at 08:00
  • Possible duplicate of [Is List a subclass of List? Why are Java generics not implicitly polymorphic?](https://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-are-java-generics-not-implicitly-po) – Lino Apr 30 '18 at 08:01

1 Answers1

2

WeakReference is needed when you need to keep a reference to a context like an activity, but if you use the context just in one method and return, then there's no need to use a WeakReference at all. Just use:

public static AnalyticsWrapper getInstance(IAnalytics iAnalytics) {
   activityName = iAnalytics.getAnalyticViewName();
}
greywolf82
  • 21,813
  • 18
  • 54
  • 108
  • @greywold82, Thanks, this is what my understanding is, i am passing activity reference to the singleton class, and calling activity methods from there. So singleton class will always have reference of that activity, and GC will not be able to clear it even after activity is destroyed. – dev90 Apr 30 '18 at 08:05
  • 1
    What you expect is the exact opposite of what `WeakReference` does – Lino Apr 30 '18 at 08:06
  • 1
    @Kirmani88 No, according to your code, the signleton class *won't* have any reference to the activity, it just calls the method grabbing the activityName and then return, no leak. A diffrent thing would be if you keep a refrence to the activty using an attribute in your singleton class of type IAnalytics – greywolf82 Apr 30 '18 at 08:09
  • 1
    @Kirmani88 Remember to accept the answer, stackoverflo is not a simple forum – greywolf82 May 01 '18 at 12:41