-1

I want to create one static object, that can be used in whole program. So I have this class for sql.

private static FeadReadDB myInstance;

public FeadReadDB(android.content.Context context){
    super(context, DB_NAME, null, DB_VERION);
    myInstance = this;
}

public static FeadReadDB getInstance(){
    return myInstance;
}

In first, I didn't have this getInstance function, but when I wrote it, and change code, I got null pointer exception. Is it possible to create something like this, let's say, init this myInstance, at beginning of program and then use in rest of program ( activities )?

ilse2005
  • 11,189
  • 5
  • 51
  • 75
Jeste
  • 37
  • 10
  • 2
    Read about Singletons – Eran Mar 01 '16 at 10:44
  • Possible duplicate of [What is an efficient way to implement a singleton pattern in Java?](http://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java) – RPresle Mar 01 '16 at 10:50

1 Answers1

1

In all probability, your intention is to make this object a singleton. The problem, however, is that you have input required in your initialization code (the constructor, in this case). This is a challenge to the typical singleton techniques.

A better approach would be to have a static initialization method that can be called by the code currently invoking the constructor:

public static void initialize(android.content.Context context) {
    FeadReadDB.myInstance = new FeadReadDB(context);
}

//The above will give you reasons to hide the constructor:
private FeadReadDB(android.content.Context context) {

    super(context, DB_NAME, null, DB_VERION);

    //As recommended, ensure that no one can call this constructor using reflection:
    if(null != myInstance) {
        throw new IllegalStateException("Cannot create multiple instances");
    }
}

//As the getter may be called before initialization, raise an exception if myInstance is null:
public static FeadReadDB getInstance(){
   if(null == myInstance) {
       throw new IllegalStateException("Initialization not done!");
   }

   return myInstance;
}

With that, all you'll have to do is ensure that your client code invokes the initialization method before calling getInstance().

ernest_k
  • 44,416
  • 5
  • 53
  • 99
  • Thanks man, problem was i didn't call getInstance function before i use getReadableDatabase... so silly – Jeste Mar 01 '16 at 11:31