什么是同时活动之间切换的Android应用程序一个单独的“实例”变量变为空的可能性有多大? [英] What are the chances a singleton's 'instance' variable becomes null in an android app while switching between Activities?
问题描述
我有一个单身,典型的设计使用静态'mInstance保持全局状态。我注意到,有时,虽然活动之间切换时,mInstance变量变为无效,并要求重新实例化,导致所有数据走空。
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粘贴:
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.
推荐答案
您需要让你的构造私人。我猜你可能会调用构造一个新的。也使您的getInstance同步。
You need to make your constructor private. I guess you may be calling a new on the constructor. Also make your getInstance synchronized.
这篇关于什么是同时活动之间切换的Android应用程序一个单独的“实例”变量变为空的可能性有多大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!