How to pass an arrayList between two intent in And

2019-09-18 07:04发布

I am new in Android and I have a question regarding intent. I want to pass an String ArrayList between two activities by using intent. I have tried this:

`
ArrayList<String> playerName = new ArrayList<>();
Intent intent = new Intent(this,Game.class);
intent.putStringArrayListExtra("Player",playerName);
startActivity(intent);`

Then I tried to receive my intent like that: `

 ArrayList<String> playerNameList= new ArrayList<>();
 playerNameList = getIntent().getStringArrayListExtra("Player");
 int listSize = playerNameList.size();
 StringBuilder str = new StringBuilder(" ");
 str.append(listSize);
 textView.setText(str);
 StringBuilder str1 = new StringBuilder(" ");
 str1.append(playerNameList.get(2));
 textView2.setText(str1);`

I can get the correct listSize; however I am not able to get any element of my arrayList. I always get the "index(0)" element. I would be really appreciated to any advice and help

2条回答
别忘想泡老子
2楼-- · 2019-09-18 07:37

you can easily to by using Gson

Intent intent = new Intent(this,Game.class);
intent.putExtra("Player",new Gson().toJson(playerName));
startActivity(intent);

at Game.class

ArrayList<String> playerNameList = playerNameList = new ArrayList<>();
String str =  getIntent().getStringExtra("Player");
playerNameList = new Gson().fromJson(str,new TypeToken<ArrayList< String >>(){}.getType());
查看更多
小情绪 Triste *
3楼-- · 2019-09-18 07:41

Check your code to add data to ArrayList playerName. The code to putStringArrayListExtra to Intent and getStringArrayListExtra from Intent is correct.

查看更多
登录 后发表回答