What are the chances a singleton's 'instance' variable becomes null in an android app while switching between Activities?

流过昼夜 提交于 2019-12-11 16:06:31

问题


I have a singleton, typical design with a static 'mInstance' to hold the global state. I notice that sometimes, while switching between activities, the mInstance variable becomes null and requires to be re-instantiated, causing all data to go empty.

Is this expected or am I doing something wrong? Is there really a chance that the static variables of a singleton would be nullified in such a scenario? I seriously doubt it and would like to hear some opinions.

Code is pasted:

public class RuleManager extends ArrayAdapter<Rule>
{
  private static RuleManager mInstance;
  private final Context context;
  public RuleManager(Context context, List<Rule> r)
  {
    super(context,R.layout.main_menu_options_list_item);
    if(r==null)r=new ArrayList<Rule>();
    this.context=context;
  }

  public static RuleManager getInstance(Context context,List<Rule> r) 
  {
      if (mInstance == null)
          mInstance = new RuleManager(context, r);
      return mInstance;
  }   
}

I just learned that storing Context like this would never let it being Garbage Collected and hence may cause a big leak.


回答1:


You need to make your constructor private. I guess you may be calling a new on the constructor. Also make your getInstance synchronized.




回答2:


A Service may be better than a Singleton if you want to hook into the LifeCycle. Here's more information from a related stackoverflow question.



来源:https://stackoverflow.com/questions/9502858/what-are-the-chances-a-singletons-instance-variable-becomes-null-in-an-androi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!