2015-08-28 35 views
0

我的一個類時,有3個屬性ArrayList的是這樣的:ArrayList的<String>空建設地塊

public class Product implements Parcelable{ 

// other properties 

private ArrayList<String> categoryIds; 
private ArrayList<String> categorySlugs; 
private ArrayList<String> categoryNames; 

public Product(){} 

// getters and setters 

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

@Override 
public void writeToParcel(Parcel dest, int flags) { 
    // writing other properties 
    dest.writeStringList(categoryIds); // here aren't null 
    dest.writeStringList(categorySlugs); 
    dest.writeStringList(categoryNames); 
} 

public static final Parcelable.Creator<Product> CREATOR = new Parcelable.Creator<Product>() { 
    public Product createFromParcel(Parcel pc) { 
     return new Product(pc); 
    } 
    public Product[] newArray(int size) { 
     return new Product[size]; 
    } 
}; 

public Product(Parcel in){ 

    // reading other properties, all correct 

    in.readStringList(categoryIds); // from here are all null 
    in.readStringList(categorySlugs); 
    in.readStringList(categoryNames); 
} 

}

閱讀的包裹構造的意見。那三個是空的,但在函數「writeToParcel」中它們不是null。所有其他屬性都是正確的。我在這裏錯過了什麼?

謝謝:)

+2

你從來沒有實例化的列表來創建一個實例。你需要private ArrayList categoryIds = new ArrayList ()'; 'new ArrayList ()'是關鍵部分,因爲這是構建對象實例的地方。 – TEK

+0

這是我第一次在包裹中使用ArrayList 。到目前爲止,我還有我的自定義類的數組:ArrayList ,無需實例化。但你是完全正確的,它的工作,謝謝!如果您將它作爲答案發布,我會接受它。 – AlbertoGarrido

+0

完成。很高興我能以某種方式提供幫助。 :) – TEK

回答

0

你永遠不會實例化列表來創建一個實例。

例如,你需要:

private ArrayList<String> categoryIds = new ArrayList<String>();

new ArrayList<String>()是關鍵部分,因爲這是你構造對象實例。

更好的是,在Product的構造函數中構造這些列表。也請考慮coding to interface。下面的代碼

0

使用閱讀列表:

categoryIds = in.createStringArrayList() 
相關問題