Vito Banovac Vito Banovac - 4 months ago 26
Android Question

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:

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:

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:

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


But I get NullPointerException when I try to retrieve extra. What I am doing wrong? Thank you for your help!

Answer

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");
...
Comments