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

Android传递ArrayList<Localizacion>对象的问题排查与解决

解决Android页面间传递ArrayList<Localizacion>对象的问题

最近在做Android开发时踩了个页面间传递自定义对象列表的坑,折腾了一阵终于理清问题根源,把过程分享出来:

问题场景

我需要在两个Activity之间传递ArrayList<Localizacion>对象,最初写了如下代码,但运行时始终无法正常获取到列表:

发送方(原页面)代码

public void marcas(View view) {
    ArrayList<Localizacion> object = new ArrayList<Localizacion>(localizaciones);
    Intent intent = new Intent(getApplicationContext(), CompraVenta.class);
    Bundle args = new Bundle();
    args.putSerializable("ARRAYLIST", (Serializable) object);
    intent.putExtra("BUNDLE", args);
    startActivityForResult(intent, RESPUESTA_ACTIVIDAD);
}

接收方(目标页面)代码

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_compra_venta);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    Intent intent = getIntent();
    Bundle args = intent.getBundleExtra("BUNDLE");
    ArrayList<Localizacion> object = (ArrayList<Localizacion>) args.getSerializable("ARRAYLIST");
    loc = object;
    enlaceInterfaz();
}

错误原因排查

一开始我怀疑是Localizacion类的序列化问题,但其实我已经给它实现了Parcelable接口——问题出在传递逻辑上:我错误地用了Serializable的方式来传递列表,完全没用到已经实现好的Parcelable,这种不匹配的传递方式导致对象无法正常解析。

正确的传递方式(基于Parcelable)

既然Localizacion已经实现了Parcelable,直接用Intent和Bundle提供的Parcelable相关方法即可,修改后的代码如下:

修改后的发送方代码

public void marcas(View view) {
    ArrayList<Localizacion> object = new ArrayList<Localizacion>(localizaciones);
    Intent intent = new Intent(getApplicationContext(), CompraVenta.class);
    intent.putParcelableArrayListExtra("LOCALIZACION_LIST", object);
    startActivityForResult(intent, RESPUESTA_ACTIVIDAD);
}

修改后的接收方代码

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_compra_venta);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    Intent intent = getIntent();
    loc = intent.getParcelableArrayListExtra("LOCALIZACION_LIST");
    enlaceInterfaz();
}

这样调整后,就能正常传递并获取ArrayList<Localizacion>对象了。

内容的提问来源于stack exchange,提问作者Bruno de Castro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:09:46