我无法解决此问题:
1)我有实现Parcelable的自定义类:
public class CityCoordinates implements Parcelable {
private double latitude;
private double longitude;
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public CityCoordinates(double latitude, double longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
public CityCoordinates(Parcel in) {
latitude = in.readDouble();
longitude = in.readDouble();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeDouble(latitude);
dest.writeDouble(longitude);
}
public static final Parcelable.Creator<CityCoordinates> CREATOR = new Parcelable.Creator<CityCoordinates>() {
public CityCoordinates createFromParcel(Parcel in) {
return new CityCoordinates(in);
}
public CityCoordinates[] newArray(int size) {
return new CityCoordinates[size];
}
};
}
2)我有一个ArrayList listItems的片段,我想发送给另一个活动:
ArrayList<CityCoordinates> listItems = new ArrayList<>();
...
Intent intent = new Intent(getActivity(), MapActivity.class);
intent.putParcelableArrayListExtra("key", listItems);
startActivity(intent);
3)这就是我在我开始的活动中检索ParcelableArrayListExtra的方法:
public class MapActivity extends ActionBarActivity {
...
ArrayList<CityCoordinates> cityCoordinatesList = getIntent().getParcelableArrayListExtra("key");
但是当我尝试检索额外的时候,我得到NullPointerException。我做错了什么?谢谢你的帮助!
答案 0 :(得分:0)
为了从意图中撤回额外内容,我应该在活动的创建中这样做。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_map_main);
...
ArrayList<CityCoordinates> cityCoordinatesList = getIntent().getParcelableArrayListExtra("key");
...
答案 1 :(得分:0)
我建议定义一个接口,让主活动实现它。将该引用传递给片段。当您想要发送数据时,只需将其传递给接口并删除该片段即可。这将节省一些时间