2013-11-24 62 views
0

我在我的Android應用程序中遇到單身問題。我已經閱讀了關於這個問題的所有帖子在Stackoverflow,但我對此感到困惑。Android單身人士和內存問題

我有一個單例表示與其他系統的接口。它的結構是這樣的:

public class Ifc 
{ 
    private static Ifc sharedIfc; 
    private String attrib; 

    public static Ifc getInstance() 
    { 
     if (sharedIfc == null) 
     { 
      sharedIfc = new Ifc(); 
      sharedIfc.attrib = ""; 
     } 
     return sharedIfc; 
    } 

    public boolean isMyAttrib(String myAttrib) 
    { 
     if(this.attrib.matches(myAttrib)) 
      return true; 
     else 
      return false; 
    } 
} 

我訪問此單是這樣的:

myIfcInstance = Ifc.getInstance(); 
boolean _isMyAttrib = myIfcInstance.isMyAttrib("example"); 

我的問題是,這個代碼不能正常工作在低內存問題的設備上運行。在這些設備中,應用程序經常崩潰,在「at.attrib.matches(myAttrib))」中使用attrib中的NullPointer錯誤。

我知道靜態數據可能會在內存不足的情況下從內存中刪除,但有可能該類不爲null,但其屬性爲空?

避免這種情況的最佳方法是什麼?也許這樣的事情?我認爲是可怕的,但它可以工作:

public static Ifc getInstance() 
    { 
     if (sharedIfc == null) 
     { 
      sharedIfc = new Ifc(); 
      sharedIfc.attrib = ""; 
     } 
     if(shared.attrib == null) shared.attrib = ""; 
     return sharedIfc; 
    } 

非常感謝!

回答

0

只有一種方式是數據由Android API保證在應用的生命週期中創建一個擴展Application的類。 http://developer.android.com/reference/android/app/Application.html

爲了獲得完整的透明度,我看到android工程師推薦單身人士,但是這種方法對於我來說非常適合應用程序關鍵數據和對象。

創建擴展應用課程後,你可以從你的應用程序的任何部分參考如下

myClass app = (myClass)getApplication(); 

在「MyClass的」類,你可以做你會在你的單身執行實現了相同的方法以上。

希望這會有所幫助。

+0

謝謝Martin。我沒有看到這個答案,因爲我的客戶最終決定忽略這個問題,因爲它只發生在非常少的Android模型以及非常特定的時刻。 – Wonton

+0

沒問題,至少它可能會幫助你在未來的項目:) –