2014-02-22 51 views
1

我有一個類管理從文件加載的數據。這個類在主Activity中初始化。當主Activity創建一個新的Activity時,新的Activity需要來自文件的數據,換句話說,它需要對管理數據的類的引用。什麼是最好的方法來做到這一點?Android - 多個活動使用的一個類

回答

0

如果一個類僅僅代表一個數據塊,它從文件中讀取,有什麼不對讓你的類單身,就像這樣:

class FileData { 
    private static final FileData instance = readFile(); 
    public static FileData getInstance() { 
     return instance; 
    } 
    private static readFile() { 
     ... // Read the file, and create FileData from it 
    } 
    public int getImportantNumber() { 
     return ... 
    } 
} 

現在你可以引用從所有其他類的數據,這樣的:

FileData.getInstance().getImportantNumber(); 
+0

我加 '如果(_instance == NULL) _instance =新的FileData();' 到'的getInstance()'所以它會實例化一次。 – MazzMan

2

是的,最好的方法是隻創建一個instance你的班級。這是Singleton設計模式。

0

1:Singleton模式
2 .:您可以使課程Parcelable。

// simple class that just has one member property as an example 
public class MyParcelable implements Parcelable { 
private int mData; 

/* everything below here is for implementing Parcelable */ 

// 99.9% of the time you can just ignore this 
public int describeContents() { 
    return 0; 
} 

// write your object's data to the passed-in Parcel 
public void writeToParcel(Parcel out, int flags) { 
    out.writeInt(mData); 
} 

// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods 
public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() { 
    public MyParcelable createFromParcel(Parcel in) { 
     return new MyParcelable(in); 
    } 

    public MyParcelable[] newArray(int size) { 
     return new MyParcelable[size]; 
    } 
}; 

// example constructor that takes a Parcel and gives you an object populated with it's values 
private MyParcelable(Parcel in) { 
    mData = in.readInt(); 
} 

}

然後你可以通過意圖送你的對象:

Intent i = new Intent(); 
i.putExtra("name_of_extra", myParcelableObject); 

,並得到它在你的第二個活動這樣的:

Intent i = getIntent(); 
MyParcelable myParcelableObject = (MyParcelable) i.getParcelableExtra("name_of_extra"); 

爲了方便我從this SO線上取得了代碼,因爲它非常好,但它也很漂亮原文如此。你甚至可以發送對象列表,但它有點複雜,需要更多示例代碼和解釋。如果這是您的目標,請詢問。對於一個對象,代碼是完全正確的。