java - 在 Android 中将 Parceables 数组写入 Parcel

标签 java android parcelable parcel

我正在尝试编写一个对象数组来实现 Parcelable进入 Parcel使用 writeParcelableArray .

我尝试编写的对象被定义为(正如您所期望的那样):

public class Arrival implements Parcelable {
    /* All the right stuff in here... this class compiles and acts fine. */
}

我正在尝试将它们写入“包裹”中:

@Override
public void writeToParcel(Parcel dest, int flags) {
    Arrival[] a;
    /* some stuff to populate "a" */
    dest.writeParcelableArray(a, 0);
}

当 Eclipse 试图编译它时,我得到了错误:

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 >

我完全不明白这个错误信息。 Parcelable 是一个接口(interface)(不是一个类),所以你不能扩展它。有人有什么想法吗?

更新: 当将 ParcelableArrayList 放入 Intent 时,我遇到了基本相同的问题>:

Intent i = new Intent();
i.putParcelableArrayListExtra("locations", (ArrayList<Location>) locations);

产量:

The method putParcelableArrayListExtra(String, ArrayList< ? extends Parcelable >) in the type Intent is not applicable for the arguments (String, ArrayList< Location >)

这可能是因为 Location 是我在上面工作的类(它包装了 Arrival),但我不这么认为。

最佳答案

实际上,您可以扩展一个接口(interface),看起来您只需要这样做。 writeParcelableArray 中的泛型参数要求扩展接口(interface)(而不是接口(interface)本身)。尝试创建一个接口(interface) MyParcelable extends Parcelable。然后使用接口(interface)声明您的数组,但 impl 应该是您的 Arrival extends MyParcelable。

关于java - 在 Android 中将 Parceables 数组写入 Parcel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1890844/

相关文章:

java - 创建 Java 单例类的 2 个实例

安卓音频搜索栏

android - API 'variant.getJavaCompile()' 已过时并已替换为 'variant.getJavaCompileProvider()' 。它将在 2019 年底被删除

java - 无法启动视频播放器 Activity

android - Scala 支持 Android 的 Parcelables 吗?

android - @Parcelize 注解和继承

java - 具有不同嵌入式服务器的 Spring Boot WAR 大小

javascript - JS 调用一个 java 方法,该方法又调用一个数据库

android - 如何在 fragment 中使用 Parcelable 获取数据?

java - 在 Java 中使用中断来解构代码