Pass the arraylist from one activity to another

2019-08-04 12:55发布

问题:

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

i have tried like this way..

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


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

Could somebody help me out @thanks

回答1:

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

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.

UPDATE

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.