2011-07-18 37 views
0

我發現了很多簡單的解決方案(比如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和標籤都是班,我從一個.jar文件導入。我怎麼能通過Intents將這些傳遞給另一個活動?我嘗試了爲我的「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()); 
} 

}

+0

AudioFile/Tag原語的成員?如果是這樣,你可以擴展你的項目中的AudioFile和Tag,併爲這些對象實現parcelable,然後你可以在你的主項目中使用它們。 – Mandel

回答

1

你可以讓你MyMP3類Parcelable這樣。確保讀取/寫入順序正確。非基元也必須是可分列的,所以你可能無法控制。或者,你可以想出你自己的序列化/反序列化。您可以使用文本格式,如JSON或XML。另一種方法是使用子類Application(確保在清單中聲明它),並將它用作掛起跨越活動的對象的地方。這會將對象保存在應用程序生命週期的內存中,因此請謹慎操作。