Android中能否在Activity间传递ArrayList<ArrayList<String>>?
传递嵌套
ArrayList<ArrayList<String>>到另一个Activity的解决方案 方法1:利用Serializable接口(最简单实现)
ArrayList本身实现了Serializable接口,嵌套的ArrayList<String>同样满足序列化要求,因此可以直接通过Intent传递:
发送端(当前Activity):
// 假设你的嵌套列表是ejemplo Intent intent = new Intent(CurrentActivity.this, TargetActivity.class); intent.putExtra("NESTED_ARRAY_LIST_KEY", ejemplo); startActivity(intent);
接收端(目标Activity):
// 在onCreate方法中获取列表 ArrayList<ArrayList<String>> receivedList = null; if (getIntent() != null) { receivedList = (ArrayList<ArrayList<String>>) getIntent().getSerializableExtra("NESTED_ARRAY_LIST_KEY"); } // 使用前可判断receivedList是否为null
注意:该方法实现简单,但序列化/反序列化性能略低于Parcelable,若列表数据量极大,建议选择下方的Parcelable方案。
方法2:自定义Parcelable包装类(性能更优)
如果追求更高的传输效率,可以创建一个持有嵌套列表的Parcelable包装类:
1. 实现Parcelable包装类
import android.os.Parcel; import android.os.Parcelable; import java.util.ArrayList; public class NestedListWrapper implements Parcelable { private ArrayList<ArrayList<String>> nestedList; public NestedListWrapper(ArrayList<ArrayList<String>> nestedList) { this.nestedList = nestedList; } protected NestedListWrapper(Parcel in) { nestedList = in.readArrayList(ArrayList.class.getClassLoader()); } public static final Creator<NestedListWrapper> CREATOR = new Creator<NestedListWrapper>() { @Override public NestedListWrapper createFromParcel(Parcel in) { return new NestedListWrapper(in); } @Override public NestedListWrapper[] newArray(int size) { return new NestedListWrapper[size]; } }; public ArrayList<ArrayList<String>> getNestedList() { return nestedList; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeList(nestedList); } }
2. 发送端传递数据
Intent intent = new Intent(CurrentActivity.this, TargetActivity.class); NestedListWrapper wrapper = new NestedListWrapper(ejemplo); intent.putExtra("WRAPPER_KEY", wrapper); startActivity(intent);
3. 接收端获取数据
NestedListWrapper wrapper = null; if (getIntent() != null) { wrapper = getIntent().getParcelableExtra("WRAPPER_KEY"); } if (wrapper != null) { ArrayList<ArrayList<String>> receivedList = wrapper.getNestedList(); // 处理获取到的列表 }
不推荐方案:全局变量
比如在自定义Application类中存储该列表,虽能实现传递,但会增加代码耦合度,且易引发内存泄漏,非必要不建议使用。
内容的提问来源于stack exchange,提问作者louisMay
相关产品推荐
相关产品推荐

