简体   繁体   English

如何在Android中的两个意图之间传递arrayList

[英]How to pass an arrayList between two intent in Android

I am new in Android and I have a question regarding intent. 我是Android的新手,我对意图有疑问。 I want to pass an String ArrayList between two activities by using intent. 我想通过使用意图在两个活动之间传递一个String ArrayList。 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; 我可以获得正确的listSize; however I am not able to get any element of my arrayList. 但是我无法获取我的arrayList的任何元素。 I always get the "index(0)" element. 我总是得到“ index(0)”元素。 I would be really appreciated to any advice and help 我将不胜感激任何建议和帮助

you can easily to by using Gson 您可以通过使用Gson轻松地

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

at Game.class 在Game.class

ArrayList<String> playerNameList = playerNameList = new ArrayList<>();
String str =  getIntent().getStringExtra("Player");
playerNameList = new Gson().fromJson(str,new TypeToken<ArrayList< String >>(){}.getType());

Check your code to add data to ArrayList playerName . 检查您的代码以将数据添加到ArrayList playerName The code to putStringArrayListExtra to Intent and getStringArrayListExtra from Intent is correct. putStringArrayListExtra为Intent并将getStringArrayListExtra从Intent转换为正确的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM