How to pass an arrayList between two intent in Android

蹲街弑〆低调 提交于 2020-01-06 17:57:45

问题


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


回答1:


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());



回答2:


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



来源:https://stackoverflow.com/questions/43791335/how-to-pass-an-arraylist-between-two-intent-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!