Parceable Arraylist of objects

前端 未结 3 1199
眼角桃花
眼角桃花 2021-01-24 21:50

I\'m trying to pass an ArrayList of Person Objects from the MainActivity to SecondActivity to print the details of the person in a custom listView adapter.

The applicati

3条回答
  •  有刺的猬
    2021-01-24 22:06

    ArrayList does not implements Parcelable, but it implements Serializable, so you can't use getParcelableExtra to receive the data, you must use getSerializableExtra instead.

    ArrayList person = (ArrayList) i.getSerializableExtra("personObject");
    

    Person class must implements Serializable too, here is the code example:

    Person implements Serializable{
       private static final long serialVersionUID = 0L;
       String id;
       String name;
    }
    

    Update:

    Another solution: use putParcelableArrayListExtra and getParcelableArrayListExtra.

    First activity:

    ArrayList list = new ArrayList();
    
    public void onButtonClick() {
        Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
        intent.putParcelableArrayListExtra("personObject", list);
        startActivity(intent);
    }
    

    Second Activity:

    ArrayList person = (ArrayList) i.getParcelableArrayListExtra("personObject");
    

    Note: Parcelable is faster than Serializable, so the second solution is better if you want to pass a lot of data.

提交回复
热议问题