0

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.

kishu27
  • 3,140
  • 2
  • 26
  • 41
  • If you implement your singleton as an enum, it can't possibly go wrong. See http://stackoverflow.com/questions/70689/efficient-way-to-implement-singleton-pattern-in-java – Graham Borland Feb 29 '12 at 16:28
  • @GrahamBorland pasted the code. Thanks for your interest – kishu27 Feb 29 '12 at 16:32

2 Answers2

1

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

Siddharth
  • 9,349
  • 16
  • 86
  • 148
  • thanks. I will implement this. If you can tellme what would 'synchronized' do, it would be great. I'm just 5 days old in Java – kishu27 Feb 29 '12 at 17:17
  • You should read up about thread synchronization. But in a few words. So more than one activity will be accessing the getInstance. This means that (by chance) if more than activity access the getInstance, you may end up with 2 instances of your singleton. Synchronized keyword ensures that this method is a critical section. Please do read up java threads sync more. – Siddharth Mar 01 '12 at 03:22
0

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.

Community
  • 1
  • 1
dbryson
  • 6,047
  • 2
  • 20
  • 20
  • Yes but I'm using this singleton as Data provider for a ListView. I guess I can keep a backup of the List that I have in a service. Is that a good practice? – kishu27 Mar 01 '12 at 06:46