问题
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