Reputation: 3349
I have an array list of JSON Objects that I'm trying to pass like so.
ArrayList<JSONObject> entryCities = new ArrayList<>();
for(int i = 0; i < entries.length(); i++){
entryCities.add(entries.getJSONObject(i));
}
Intent intent = new Intent(UnitedStatesActivity.this, StateActivity.class);
intent.putExtra("object", entryCities);
startActivity(intent);
I know this doesn't work and that I need to make my array, or the JSON Object in the array parcelable. I started looking at the documentation and have come up with this class that I am wanting to pass the ArrayList<JSONObject>
into, but I'm not sure what I'm supposed to be adding in my writeToParcel()
method.
Am I writing out the specific values of the JSON Object I want to pull? i.e.
out.object.getString("string")
and then passing my parcelable object on to the next activity? I'm just not sure what the content of the method should be in the context of making JSON Objects parcelable.
public class StateParcelable extends JSONObject implements Parcelable {
ArrayList<JSONObject> list;
public StateParcelable(ArrayList<JSONObject> list){
this. list = list;
}
public void writeToParcel(Parcel out, int flags) {
}
public int describeContents(){
return 0;
}
public static final Parcelable.Creator<StateParcelable> CREATOR
= new Parcelable.Creator<StateParcelable>() {
public StateParcelable createFromParcel(Parcel in) {
return new StateParcelable(in);
}
public StateParcelable[] newArray(int size) {
return new StateParcelable[size];
}
};
private StateParcelable(Parcel in) {
}
Upvotes: 0
Views: 5655
Reputation: 6834
Since you already have (what appears to be) a JSONArray of JSONObjects, why not just convert it to a String, pass that, and rebuild the JSONArray from that?
Intent intent = new Intent(UnitedStatesActivity.this, StateActivity.class);
intent.putExtra("object", entries.toString());
startActivity(intent);
And then in the following Activity:
JSONArray entries = new JSONArray(getIntent().getStringExtra("object"));
Otherwise, yes, you'd have to loop through and serialize the individual items in your ArrayList and then rebuild and add them to the list.
Also, a side note, you can pass the individual JSONObjects the same way: via toString()
and new JSONObject(getIntent().getStringExtra("object"))
, respectively.
Upvotes: 5