Java Android-一个由多个活动使用的类

Java Android-一个由多个活动使用的类,java,android,class,android-activity,Java,Android,Class,Android Activity,我有一个类来管理从文件加载的数据。该类在主活动中初始化。当主活动创建新活动时,新活动需要来自文件的数据,换句话说,它需要对管理数据的类的引用。最好的方法是什么?是的,最好的方法是只创建一个类的实例。这是单例设计模式。单例模式应该适合您的需要。这基本上是一个只能实例化一次并管理实例本身的类,因此您可以从任何地方获得它 类似这样的教程将帮助您入门:如果一个类只是表示它从文件中读取的一块数据,那么将您的类设置为单例并没有什么错,如下所示: class FileData { private st

我有一个类来管理从文件加载的数据。该类在主活动中初始化。当主活动创建新活动时,新活动需要来自文件的数据,换句话说,它需要对管理数据的类的引用。最好的方法是什么?

是的,最好的方法是只创建一个类的
实例。这是单例设计模式。

单例
模式应该适合您的需要。这基本上是一个只能实例化一次并管理实例本身的类,因此您可以从任何地方获得它


类似这样的教程将帮助您入门:

如果一个类只是表示它从文件中读取的一块数据,那么将您的类设置为单例并没有什么错,如下所示:

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();
现在,您可以引用所有其他类中的数据,如下所示:

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();
1.:单例模式
2.:你可以把这个班级打包

// 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 = getIntent();
MyParcelable myParcelableObject = (MyParcelable) i.getParcelableExtra("name_of_extra");
为了方便起见,我从SO线程中获取了代码,因为它非常好,但也非常基本。您甚至可以通过意向发送对象列表,但这有点复杂,需要更多的示例代码和解释。如果这是你的目标,请询问。对于一个对象,代码是完全正确的。

I添加了
if(_instance==null)_instance=newfiledata()
getInstance()
,因此它将只实例化一次。