问题
I'm trying to write an array of objects that implement Parcelable into a Parcel using writeParcelableArray.
The objects I'm trying to write are defined (as you'd expect) as:
public class Arrival implements Parcelable {
/* All the right stuff in here... this class compiles and acts fine. */
}
And I'm trying to write them into a `Parcel' with:
@Override
public void writeToParcel(Parcel dest, int flags) {
Arrival[] a;
/* some stuff to populate "a" */
dest.writeParcelableArray(a, 0);
}
When Eclipse tries to compile this I get the error:
Bound mismatch: The generic method writeParcelableArray(T[], int) of type Parcel is not applicable for the arguments (Arrival[], int). The inferred type Arrival is not a valid substitute for the bounded parameter < T extends Parcelable >
I completely don't understand this error message. Parcelable
is an interface (not a class) so you can't extend it. Anyone have any ideas?
UPDATE: I'm having basically the same problem when putting an ArrayList
of Parcelable
s into an Intent
:
Intent i = new Intent();
i.putParcelableArrayListExtra("locations", (ArrayList<Location>) locations);
yields:
The method putParcelableArrayListExtra(String, ArrayList< ? extends Parcelable >) in the type Intent is not applicable for the arguments (String, ArrayList< Location >)
This may be because Location
was the class I was working on above (that wraps the Arrival
s), but I don't think so.
回答1:
Actually, you can extend an interface, and it looks like you need to do just that. The generics parameter in writeParcelableArray is asking for an extended interface (not the interface itself). Try creating an interface MyParcelable extends Parcelable. Then declaring your array using the interface, but the impl should be your Arrival extends MyParcelable.
回答2:
It turns out it just wanted me to build an array of Parcelables. To use the example from the question:
@Override
public void writeToParcel(Parcel dest, int flags) {
Parcelable[] a;
/*
some stuff to populate "a" with Arrival
objects (which implements Parcelable)
*/
dest.writeParcelableArray(a, 0);
}
回答3:
I know the problem is solved but my solution was other so I'm posting it here: in my case Eclipse automatically imported wrong package because of classes names abiguity(some dom.Comment instead of my Comment class).
来源:https://stackoverflow.com/questions/1890844/writing-arrays-of-parcelables-to-a-parcel-in-android