0

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

Magesh Pandian
  • 8,789
  • 12
  • 45
  • 60
Aybars
  • 395
  • 2
  • 11
  • 1
    Duplicate of http://stackoverflow.com/questions/2091465/how-do-i-pass-data-between-activities-in-android-application?rq=1 – Ivan Pronin May 04 '17 at 19:32
  • 1
    Possible duplicate of [How do I pass data between Activities in Android application?](http://stackoverflow.com/questions/2091465/how-do-i-pass-data-between-activities-in-android-application) – Bobulous May 04 '17 at 19:48
  • I think I am able to start intent and send data. Because I can get the size of my arrayList. The problem is accessing to data. – Aybars May 04 '17 at 19:57

2 Answers2

2

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());
ZeroOne
  • 8,996
  • 4
  • 27
  • 45
0

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

Anh Vu
  • 219
  • 3
  • 10