Android中Intent传递Surface对象接收时返回NULL问题求助
Intent传递对象接收为NULL的问题解决
我看你遇到了从SurfaceInspectionListActivity向AddSurfaceInspectionActivity传递对象时,接收方拿到NULL的问题,咱们来一步步理清问题根源,给出可行的解决方案:
问题根源分析
你在发送方直接把自定义对象surfaceObject通过intent.putExtra("myjsonSurfaceObject2", surfaceObject)传递,但接收方却用getStringExtra去获取——这两个操作完全不匹配!
putExtra(String, Object)对于非基本类型/字符串的对象,默认会用Serializable机制来序列化对象,但你接收时却尝试按字符串类型读取,自然拿不到数据,返回NULL。哪怕你用Serializable传递,也得用getSerializableExtra来接收,而不是getStringExtra。
解决方案一:用Gson将对象转为JSON字符串传递(适配你现有代码思路)
这是你代码里尝试的方向,但发送方漏了将对象转为JSON字符串的步骤,导致接收方拿不到有效字符串。
发送方修改代码:
public void addSurfaceInspection(View view) { // 先把自定义对象转为JSON字符串 Gson gson = new Gson(); String surfaceObjJson = gson.toJson(surfaceObject); Intent intent = new Intent(SurfaceInspectionListActivity.this, AddSurfaceInspectionActivity.class); intent.putExtra("myjsonSurfaceObject2", surfaceObjJson); startActivity(intent); finish(); }
接收方代码(你现有的代码就可以正常工作了):
Gson gson = new Gson(); surfaceObj = gson.fromJson(getIntent().getStringExtra("myjsonSurfaceObject2"), Surfaces.class);
解决方案二:让Surfaces类实现Parcelable(Android官方推荐,性能更优)
如果不想用JSON转字符串,Android推荐用Parcelable来传递自定义对象,比Serializable效率更高。
第一步:修改Surfaces类实现Parcelable接口
public class Surfaces implements Parcelable { // 你的类成员变量,示例: private String inspectionId; private String surfaceName; // 其他业务字段... // 空构造函数 public Surfaces() {} // 从Parcel中读取数据的构造函数 protected Surfaces(Parcel in) { inspectionId = in.readString(); surfaceName = in.readString(); // 按顺序读取所有成员变量 } // Parcelable必备的Creator public static final Creator<Surfaces> CREATOR = new Creator<Surfaces>() { @Override public Surfaces createFromParcel(Parcel in) { return new Surfaces(in); } @Override public Surfaces[] newArray(int size) { return new Surfaces[size]; } }; @Override public int describeContents() { return 0; // 一般返回0即可,除非包含文件描述符 } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(inspectionId); dest.writeString(surfaceName); // 按顺序写入所有成员变量 } // 你的Getter、Setter方法 public String getInspectionId() { return inspectionId; } public void setInspectionId(String inspectionId) { this.inspectionId = inspectionId; } // 其他Getter/Setter... }
第二步:发送方传递Parcelable对象
public void addSurfaceInspection(View view) { Intent intent = new Intent(SurfaceInspectionListActivity.this, AddSurfaceInspectionActivity.class); intent.putExtra("mySurfaceObject", surfaceObject); startActivity(intent); finish(); }
第三步:接收方获取Parcelable对象
// Android 33以下版本 surfaceObj = getIntent().getParcelableExtra("mySurfaceObject"); // Android 33及以上版本(推荐显式指定类型) // surfaceObj = getIntent().getParcelableExtra("mySurfaceObject", Surfaces.class);
额外注意点
- 调试时看到Intent中有数据,是因为调试工具显示的是Serializable格式的对象,但你用
getStringExtra读取时类型不匹配,所以返回NULL。 - 如果一定要用Serializable,只需让Surfaces类实现
Serializable接口,发送方直接传对象,接收方用(Surfaces) getIntent().getSerializableExtra("key")即可,但Parcelable是Android官方更推荐的方案。
内容的提问来源于stack exchange,提问作者Raj Sharma
相关产品推荐
相关产品推荐

