2016-12-07 52 views
2

我有一個叫做服務類,它是用來利用此構造函數創建服務對象傳和ArrayList <Service>

public Service(int id, String service_name, String service_code) { 
    this.id = id; 
    this.service_name = service_name; 
    this.service_code = service_code; 
} 

然後創建一個列表呼叫服務列表與以下簽名

List<Service> serviceList = new ArrayList<Service> 

我試圖通過Intent對象通過此ArrayList這樣

Intent i = new Intent(Classname.this, anotherClass.class); 
i.putExtras("serviceList",serviceList); 
startActivity(i); 

但它失敗。我通過意向傳遞ArrayList對象的方式是什麼?

回答

1

您的自定義類必須實現ParcelableSerializable才能在意圖中進行序列化/反序列化。

Service類有看起來像這樣的例子(使用的發電機http://www.parcelabler.com/

public class Service implements Parcelable { 
private int id; 
private String service_name; 
private String service_code; 
public Service(int id, String service_name, String service_code) { 
this.id = id; 
this.service_name = service_name; 
this.service_code = service_code; 
} 


protected Service(Parcel in) { 
    id = in.readInt(); 
    service_name = in.readString(); 
    service_code = in.readString(); 
} 

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

@Override 
public void writeToParcel(Parcel dest, int flags) { 
    dest.writeInt(id); 
    dest.writeString(service_name); 
    dest.writeString(service_code); 
} 

@SuppressWarnings("unused") 
public static final Parcelable.Creator<Service> CREATOR = new Parcelable.Creator<Service>() { 
    @Override 
    public Service createFromParcel(Parcel in) { 
     return new Service(in); 
    } 

    @Override 
    public Service[] newArray(int size) { 
     return new Service[size]; 
    } 
}; 

}

然後你可以使用getIntent().getParcelableArrayListExtra()與鑄造

ArrayList<Service> serviceList= intent.<Service>getParcelableArrayList("list")); 

爲了發送您使用它是這樣的

intent.putParcelableArrayListExtra("list", yourServiceArrayList); 

注意,yourServiceArrayList應該是一個ArrayList

如果列表中你可以通過

intent.putParcelableArrayListExtra("list", (ArrayList<? extends Parcelable>) yourServiceArrayList);

+0

如何發送的parcalable意圖 – nifCody

+0

@nifCody基本上是這樣的'intent.putParcelableArrayListExtra(」 list「,yourServiceArrayList)' –

+0

我們是否需要轉換yourServiceArrayList – nifCody

1

您可以使用parcelable接口「服務」類,併發送對象通過

意圖使用'putParcelableArrayListExtra'方法並檢索數據您可以使用

'getParcelableArrayListExtra'

供您參考 refer this鏈接

1

與序列化的實施對象類。 例如。

class abc implements Serializable{ 
//your code 
} 

那就試試這個代碼

ArrayList<abc> fileList = new ArrayList<abc>(); 
Intent intent = new Intent(MainActivity.this, secondActivity.class); 
intent.putSerializable("arraylisty",filelist); 
startActivity(intent); 

和對方收到意向像

your arraylist objact=intent.getSerializableExtra(String name) 
相關問題