2

In the first activity I have an ArrayList that has to be passed to a second activity.

this is the first activity:

public ArrayList<ItemContact> selectedContacts = new ArrayList<>(); //filled in the rest of the code

Intent intent = new Intent(this, SummaryActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("selectedContacts", selectedContacts);
intent.putExtra("selectedContacts", bundle);
startActivity(intent);

In the second activity:

ArrayList<ItemContact> selectedContacts = new ArrayList<>();

selectedContacts = (ArrayList<ItemContact>)getIntent().getExtras().getSerializable("selectedContacts") ;

The problem is that selectedContacts in the second activity is always null How can i fix it?

EDIT: ItemContact already implements Serializable but still doesn't work

Ravazz
  • 93
  • 6
  • Here probably the answer: https://stackoverflow.com/a/23647471/2910520 or if you already implemented the correct interface you are reading the wrong value from the intent – MatPag Nov 15 '19 at 00:47

2 Answers2

2

Your Object should implements Serializable

class ItemContact implements Serializable {

  ......
} 

first activity

    public ArrayList<ItemContact> selectedContacts = new ArrayList<>(); 

    Intent intent = new Intent(this, SummaryActivity.class);
    Bundle bundle = new Bundle();

    bundle.putSerializable("selectedContacts", selectedContacts);
    intent.putExtras(bundle);
    startActivity(intent);

second activity

    ArrayList<ItemContact> selectedContacts = new ArrayList<>();

    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();

    selectedContacts = (ArrayList<ItemContact>)bundle.getSerializable("selectedContacts");

Hope this helps.

GHH
  • 1,713
  • 1
  • 8
  • 21
0

Use Parcelable than serializable for better speed and passing multiple object data through the activities.

class ItemContact implements Parcelable {

 ......
} 

first activity

public ArrayList<ItemContact> selectedContacts = new ArrayList<>(); 
Intent intent = new Intent(this, SummaryActivity.class);
intent.putParcelableArrayListExtra("selectedContacts", selectedContacts);
startActivity(intent);

second activity

ArrayList<ItemContact> selectedContacts = new ArrayList<>();

Intent intent = getIntent();

selectedContacts = (ArrayList<ItemContact>)intent.getParcelableArrayListExtra("selectedContacts");

If you want serializable then use the below code. Implement the class with Serializable.

first activity

public ArrayList<ItemContact> selectedContacts = new ArrayList<>(); 
Intent intent = new Intent(this, SummaryActivity.class);
intent.putExtra("selectedContacts", selectedContacts);
startActivity(intent);

second activity

ArrayList<ItemContact> selectedContacts = new ArrayList<>();

Intent intent = getIntent();

selectedContacts = (ArrayList<ItemContact>)intent.getSerializableExtra("selectedContacts");
SURYA N
  • 299
  • 2
  • 16