我在我的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;
}
非常感謝!
謝謝Martin。我沒有看到這個答案,因爲我的客戶最終決定忽略這個問題,因爲它只發生在非常少的Android模型以及非常特定的時刻。 – Wonton
沒問題,至少它可能會幫助你在未來的項目:) –