将数组列表从一个活动传递到另一个活动 [英] Pass the arraylist from one activity to another

查看:43
本文介绍了将数组列表从一个活动传递到另一个活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将完整的数组列表从一个活动传递到另一个活动.

I am trying to pass the complete arraylist from one activity to another.

我试过这样..

arraylist=new ArrayList<HashMap<String,Object>>();


    Intent i= new Intent(ListActivity.this,search.class);
               i.putExtra("arraylist", arraylist);
               startActivity(i);

有人能帮我吗@thanks

Could somebody help me out @thanks

推荐答案

这将不起作用,因为 Java 中的 Object 类不可序列化.有关原因的解释,请参阅这个问题.

This will not work because the Object class in Java is not serializable. See this question for an explanation as to why.

Intent.putExtra() 方法需要一个实现可序列化接口的类型,Object 没有实现这个,因此它不会工作.我建议不要使用 HashMap,而是将 Object 替换为实现 Serializable 接口的更具体的类型.请参阅此教程了解如何执行此操作.

The Intent.putExtra() method requires a type that implements the serializable interface, Object does not implement this so consequently it will not work. I would suggest rather than having a HashMap<String,Object> you replace the Object with a more specific type that implements the Serializable interface. See this tutorial for how to do this.

更新

如果您传递的数据很大,那么与序列化和反序列化相关的开销可能相当大.因此,使用静态单例类来存储数组列表可能是值得的.下面的代码示例展示了如何实现这一点:

If the data you are passing is large there could be a fairly significant overhead associated with serializing and deserializing. Consequently it might be worth using a Static Singleton class to store the arraylist. The code sample below shows how you could implement this:

public class DataStore {
    private static final DataStore instance = new DataStore ();
    private arraylist = new ArrayList<HashMap<String,Object>>();

    //Private constructor
    private DataStore () {}

    //Class is only accessible through this method
    public static Singleton getInstance() {
        return instance;
    }

    //Accessors for your data
    private ArrayList<HashMap<String,Object>> getArrayList()
    {
         return arraylist;
    }

    private void setArrayList(ArrayList<HashMap<String,Object>> value)
    {
         arraylist = value;
    }
}

这里有一个教程,供参考静态单例.

For reference here is a tutorial on static singletons.

这篇关于将数组列表从一个活动传递到另一个活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆