You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从Firebase Firestore获取的对象列表在Intent传递时解包异常

问题分析

出现Unmarshalling unknown type code异常的核心原因是:Firestore通过toObject(Watch.class)生成的对象,包含了Parcelable序列化不支持的字段或代理类元数据,而静态数据是纯自定义Watch实例,因此能正常传递。最常见的场景是Watch类中包含Firestore的Timestamp类型字段(该类型未实现Parcelable接口),或者Firestore返回的对象带有内部附加信息的代理实例。

解决方案

1. 修复Watch类的Parcelable实现,处理所有字段

确保Watch类的所有字段都正确实现Parcelable接口,尤其是Firestore映射的字段:

  • 若使用Java手动实现Parcelable,需在writeToParcel中写入所有字段,在CREATOR的createFromParcel中按对应顺序读取;
  • 若涉及Firestore的Timestamp类型,需将其转换为可Parcelable的类型(如Long时间戳或Date)。

示例Watch类实现:

public class Watch implements Parcelable {
    private String id;
    private String name;
    private long createTime; // 用Long存储时间戳替代Firestore的Timestamp

    // 手动从Firestore文档构建实例
    public static Watch fromFirestoreDoc(QueryDocumentSnapshot doc) {
        Watch watch = new Watch();
        watch.id = doc.getId();
        watch.name = doc.getString("name");
        Timestamp ts = doc.getTimestamp("createTime");
        watch.createTime = ts != null ? ts.getSeconds() : 0;
        return watch;
    }

    // Parcelable核心实现
    protected Watch(Parcel in) {
        id = in.readString();
        name = in.readString();
        createTime = in.readLong();
    }

    public static final Creator<Watch> CREATOR = new Creator<Watch>() {
        @Override
        public Watch createFromParcel(Parcel in) {
            return new Watch(in);
        }

        @Override
        public Watch[] newArray(int size) {
            return new Watch[size];
        }
    };

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(id);
        dest.writeString(name);
        dest.writeLong(createTime);
    }

    @Override
    public int describeContents() {
        return 0;
    }
}

2. 手动复制Firestore数据到纯Watch实例

不要直接使用document.toObject(Watch.class),而是手动提取字段创建新的Watch对象,避免Firestore返回代理类:

// MainActivity中替换原循环逻辑
for (QueryDocumentSnapshot document : task.getResult()) {
    // 手动构建纯Watch实例,规避Firestore代理类问题
    Watch watch = Watch.fromFirestoreDoc(document);
    watches.add(watch);
}

3. 大数据列表的替代方案(可选优化)

如果Watch列表数据量较大,Intent传递Parcelable列表可能触发TransactionTooLargeException,建议改用ViewModel、内存缓存单例或本地数据库(如Room)共享数据,而非通过Intent传递。

验证步骤
  1. 替换Firestore获取Watch实例的方式,使用手动构建逻辑;
  2. 确认Watch类的Parcelable实现覆盖所有字段,无遗漏;
  3. 重新运行项目,检查Intent传递是否正常。

内容的提问来源于stack exchange,提问作者Nour

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 13:35:19