2016-03-01 76 views
-1

我想創建一個靜態對象,可以在整個程序中使用。所以我有這個類的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; 
} 

在第一,我沒有這樣的getInstance功能,但是當我寫它,改變代碼,我得到空指針異常。是否可以創建類似這樣的東西,比方說,在程序開始時初始化myInstance,然後在程序(活動)的其餘部分使用?

+2

閱讀關於Singletons – Eran

+0

[在Java中實現單例模式的有效方法是什麼?](http://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-在java中實現單一模式) – RPresle

回答

1

在所有可能情況下,您的意圖是將此對象設置爲單例。 然而,問題在於,您的初始化代碼(此例中爲構造函數)需要輸入。這對典型的單身技術來說是一個挑戰。

一個更好的辦法是有一個靜態初始化方法,可以通過代碼調用當前調用構造函數:

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; 
} 

就這樣,所有你需要做的是確保你的客戶端代碼在調用getInstance()之前調用初始化方法。

+0

謝謝你,問題是我沒有在使用getReadableDatabase之前調用getInstance函數......太愚蠢了 – Jeste

相關問題