简体   繁体   English

Android:使用Parcerable将自定义对象的ArrayList从片段发送到活动

[英]Android: Send ArrayList of custom objects from fragment to activity using Parcerable

I have a problem making this to work: 我有一个问题,使这个工作:

1) I have custom class that implements Parcelable: 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) I have a fragment with ArrayList listItems that I want to send to another activity: 2)我有一个ArrayList listItems片段,我想发送给另一个活动:

ArrayList<CityCoordinates> listItems = new ArrayList<>();
...
Intent intent = new Intent(getActivity(), MapActivity.class);
            intent.putParcelableArrayListExtra("key", listItems);
            startActivity(intent);

3) This is how I retrieve ParcelableArrayListExtra in the activity I started: 3)这是我在我开始的活动中检索ParcelableArrayListExtra的方法:

public class MapActivity extends ActionBarActivity {
...
ArrayList<CityCoordinates> cityCoordinatesList = getIntent().getParcelableArrayListExtra("key");

But I get NullPointerException when I try to retrieve extra. 但是当我尝试检索额外的时候,我得到NullPointerException。 What I am doing wrong? 我做错了什么? Thank you for your help! 谢谢您的帮助!

In order to retreive extras from intent I should've done so inside onCreate of the activity. 为了从意图中撤回额外内容,我应该在活动的创建中完成。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_map_main);
...
    ArrayList<CityCoordinates> cityCoordinatesList = getIntent().getParcelableArrayListExtra("key");
...

I would suggest define an interface and let the main activity implement it. 我建议定义一个接口,让主活动实现它。 Pass that reference to the fragment. 将该引用传递给片段。 when you want to send the data, just pass it through interface and remove the fragment. 当您想要发送数据时,只需将其传递给接口并删除该片段即可。 This will save some time 这将节省一些时间

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM