Android: send ArrayList of custom objects from fragment to activity using Parcerable

I have a problem, this works:

1) I have a custom class that implements 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 snippet with an ArrayList of listItems that I want to send to another activity:

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

      

3) This is how I retrieve the ParcelableArrayListExtra at the start:

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

      

But I get a NullPointerException when I try to get more information. What am I doing wrong? Thanks for the help!

+3


source to share


2 answers


In order to distract from intent, I had to do this inside the onCreate activity.



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

      

0


source


I would suggest defining an interface and letting the main activity implement it. Pass this link to the snippet. when you want to send data, just pass it through the interface and remove the fragment. It will save time



0


source







All Articles