简体   繁体   中英

How to pass an arrayList between two intent in Android

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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