如何在活动之间传递自定义类

时间:2011-07-18 23:27:14

标签: java android android-layout

我找到了许多简单的解决方案(例如Intent.putExtra(String,String)和Bundle.putString(String,String)),但这对我的情况没有帮助。

我有一个名为MyMP3的类,它包含非基本类型。我需要为MyMP3传递以下内容......

private AudioFile audioFile;
private Tag tag;
private int index;
private boolean saved, startedWithLyrics;
private String id3lyrics;

AudioFile和Tag都是我从.jar文件导入的类。如何通过Intents将这些传递给另一个Activity?我试图为我的“MyMP3”类实现Parcelable,但我不确定如何在不传递原始类型时正确使用这些方法。

你能帮助我看看下面的代码并尝试告诉我如何正确使用Parcelable和我的自定义类吗?如何在writeToParcel函数中设置Parcel以及如何在另一个Activity中正确检索该类?

下面是我的代码(至少重要的部分)。我已经尝试了几天不同的事情了,但是我无法让它发挥作用。请帮帮我!

public class MyMP3 extends AudioFile implements Parcelable
{
private AudioFile audioFile;
private Tag tag;
private int index;
private boolean saved, startedWithLyrics;
private String id3lyrics;

public MyMP3(File f, int index)
{
    this.audioFile = AudioFileIO.read(f);
    this.tag = this.audioFile.getTag();
    this.index = index;
    this.saved = false;
    this.id3lyrics = getLyrics();
}

@Override
public int describeContents()
{
    return 0;
}

@Override
public void writeToParcel(Parcel out, int flats)
{
    /* This method does not work, but I do not know how else to implement it */

    Object objects[] = {this.audioFile, this.tag, this.index, this.saved, this.startedWithLyrics, this.id3lyrics};
    out.writeArray(objects);
}

public static final Parcelable.Creator<MyMP3> CREATOR = new Parcelable.Creator<MyMP3>()
{
    public MyMP3 createFromParcel(Parcel in)
    {
        /* Taken from the Android Developer website */
        return new MyMP3(in);
    }

    public MyMP3[] newArray(int size)
    {
        /* Taken from the Android Developer website */
        return new MyMP3[size];
    }
};

private MyMP3(Parcel in)
{
        /* This method probable needs changed as well */
    Object objects[] = in.readArray(MyMP3.class.getClassLoader());
}

}

1 个答案:

答案 0 :(得分:1)

你可以像这样使你的MyMP3类Parcelable。确保您的读/写顺序正确。非基元也必须是Parcelable,所以不幸的是你可能无法控制它。或者,您可以提出自己的序列化/反序列化。您可以使用文本格式,如JSON或XML。另一种方法是使用子类Application(确保在清单中声明它)并使用它作为挂起跨越Activities的对象的地方。这会将对象保留在内存中以适应应用程序的生命周期,因此请小心这样做。