Instantiate singleton class objects in Android

950 views Asked by At

Can anyone tell me where to instantiate a singleton class object like ArrayList?

I am trying to instantiate in the onCreate() method but its not instantiated. Can any one tell me where to allocate it?

public class SharedVariables extends Application 
{
public static ArrayList<ArrayList<Map<String,String>>>  ArrayOfImageUrlDicts;
public static ArrayList<ArrayList<Map<String,String>>> ArrayOfImageNameDicts;

@Override
public void onCreate()
{
    super.onCreate();
    ArrayOfImageUrlDicts  = new ArrayList<ArrayList<Map<String,String>>>(); 
    ArrayOfImageNameDicts = new ArrayList<ArrayList<Map<String,String>>>();
}
}
2

There are 2 answers

0
Niklas Schnelle On BEST ANSWER

This is actually not a real Singelton (see Wikipedia for an accurate Description of Singeltons) but a normal static variable. If you want to usemore static variables you may consider using this as it makes things much more beautiful. However to answer your concrete question you can either use a static block where you initialize those variables or initialize them directly after decleration.

public class SharedVariables extends Application 
{
   public static ArrayList<ArrayList<Map<String,String>>>  ArrayOfImageUrlDicts = new ArrayList<ArrayList<Map<String,String>>>();
   public static ArrayList<ArrayList<Map<String,String>>> ArrayOfImageNameDicts = new ArrayList<ArrayList<Map<String,String>>>();

   @Override
   public void onCreate()
   {
      super.onCreate();
   }
}

or

public class SharedVariables extends Application 
{
   public static ArrayList<ArrayList<Map<String,String>>>  ArrayOfImageUrlDicts;
   public static ArrayList<ArrayList<Map<String,String>>> ArrayOfImageNameDicts;
   static 
   {
      ArrayOfImageUrlDicts = new ArrayList<ArrayList<Map<String,String>>>();
      ArrayOfImageNameDicts = = new ArrayList<ArrayList<Map<String,String>>>();
   }
   @Override
   public void onCreate()
   {
      super.onCreate();
   }
}
0
Harinder On
public class SharedVariables extends Application 
{

ModelSingleTonclass obj;

public static ArrayList<ArrayList<Map<String,String>>>  ArrayOfImageUrlDicts;
public static ArrayList<ArrayList<Map<String,String>>> ArrayOfImageNameDicts;

@Override
public void onCreate()
{
    super.onCreate();

obj=ModelSingleTonclass.getInstance();

    ArrayOfImageUrlDicts  = new ArrayList<ArrayList<Map<String,String>>>(); 
    ArrayOfImageNameDicts = new ArrayList<ArrayList<Map<String,String>>>();
}
}