issue to pass arraylist from an intent to another

2019-09-11 06:34发布

Before asking here, i first search how to pass an arraylist from an intent to another. Thanks to one of the post made on SO, I thought i found a way to do so.

The thing is, when i try to display the elements from the arraylist of my target activity, i only get one of the numerous elements i originally have in my departure activity.

To put it in clear, here is my code in my fisrt activity :

HashMap map = new HashMap<String,String>();

map.put("key1","value1");
map.put("key2","value2");

arrayList.add(map);
Log.d("arrayList", String.valueOf(arrayList));

In the logcat, I have the expected elements :

D/arrayList:: [{"key1":"value1"},{"key2","value2"}

Then, i pursue with this :

Intent intent = new Intent(MyFirstActivity.this,MySecondActivity.class);
intent.putExtra("arrayList",arrayList);

Now, this is my second activity where should be the received elements.

Intent intent = getIntent();
arrayList = (ArrayList<HashMap<String,String>>) getIntent().getSerializableExtra("arrayList");
Log.d("arraySecondActivity", String.valueOf(arrayList));

In the logcat, only my second item is display :

D/arraySecondActivity: [{key2=value2}]

and i don't know why ... does someone maybe know ?

thanks !

2条回答
神经病院院长
2楼-- · 2019-09-11 07:16

Suppose strinclude is a simple arraylist of integers.

ArrayList<Integer> strinclude=new ArrayList<Integer>();

Activity 1:

//Here I am sending the arraylist to Activity2
 Intent i=new Intent(MainActivity.this,ResultActivity.class);
 i.putExtra("include",strinclude);
startActivity(i);

Activity 2:

  //Here I am recieving the arraylist from Activity1
ArrayList<Integer> strinclude=new ArrayList<Integer>();
strinclude=(ArrayList<Integer>) getIntent().getSerializableExtra("include");

Thats it.

查看更多
smile是对你的礼貌
3楼-- · 2019-09-11 07:19

intent.putExtra("arrayList",arrayList); this wrong in your code. Serializable the arraylist before pass like below

Try this code

 ArrayList<Object> object = new ArrayList<Object>();
 Intent intent = new Intent(Current.class, next.class);
 Bundle args = new Bundle();
 args.putSerializable("ARRAYLIST",(Serializable)object);
 intent.putExtra("BUNDLE",args);
 startActivity(intent);

In the next.class

 Intent intent = getIntent();
 Bundle args = intent.getBundleExtra("BUNDLE");
 ArrayList<Object> object = (ArrayList<Object>)  args.getSerializable("ARRAYLIST");
查看更多
登录 后发表回答