2015-07-11 142 views
0

我创建了以下parcelable对象:创建parcelable的正确方法是什么?

public class ViewModel implements Parcelable { 

private String image, price, credit, title, description, id; 

public ViewModel(String image, String price, String credit, String title, String description, String id) { 
    this.image = image; 
    this.price = price; 
    this.credit = credit; 
    this.title = title; 
    this.description = description; 
    this.id = id; 
} 

public String getPrice() { 
    return price; 
} 

public String getCredit() { 
    return credit; 
} 

public String getDescription() { 
    return description; 
} 

public String getId() { 
    return id; 
} 

public String getTitle() { 
    return title; 
} 

public String getImage() { 
    return image; 
} 

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

@Override 
public void writeToParcel(Parcel dest, int flags) { 
    dest.writeStringArray(new String[] { 
      this.image, 
      this.price, 
      this.credit, 
      this.title, 
      this.description, 
      this.id 
    }); 
} 

/** Static field used to regenerate object, individually or as arrays */ 
public static final Parcelable.Creator<ViewModel> CREATOR = new Parcelable.Creator<ViewModel>() { 
    public ViewModel createFromParcel(Parcel pc) { 
     return new ViewModel(pc); 
    } 
    public ViewModel[] newArray(int size) { 
     return new ViewModel[size]; 
    } 
}; 

/**Creator from Parcel, reads back fields IN THE ORDER they were written */ 
public ViewModel(Parcel pc){ 
    image = pc.readString(); 
    price = pc.readString(); 
    credit = pc.readString(); 
    title = pc.readString(); 
    description = pc.readString(); 
    id = pc.readString(); 
} 

}

现在我通过束发的ViewModelArrayList

bundle.putParcelableArrayList("products", viewModels); 

这有什么错,我在做什么?因为我得到了空Bundle Arguments,但是如果我发送一个简单的字符串,那么一切正常。

回答

0

使这一变化:

@Override 
public void writeToParcel(Parcel dest, int flags) { 
    dest.writeString(this.image); 
    dest.writeString(this.price); 
    dest.writeString(this.credit); 
    dest.writeString(this.title); 
    dest.writeString(this.description); 
    dest.writeString(this.id); 
} 


getIntent().getParcelableArrayListExtra("product"); // get the list 
+0

一样的东西,包是空的'getArguments()' – FilipLuch

0

您试图检索parcelable的ArrayList。您需要检索您创建的可分段的ViewModel对象。变化:

bundle.putParcelableArrayList("product", viewModels); 

getIntent().getParcelableArrayList("product"); 

到:

bundle.putParcelable("product", viewModels); 

getIntent().getParcelable("product"); 
相关问题