2017-05-04 69 views
0

我是Android新手,我有一个关于intent的问题。我想通过使用intent在两个活动之间传递一个String ArrayList。我曾经尝试这样做:如何在Android中的两个intent之间传递arrayList

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

然后我试图接受我的意图这样的: `

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

我能得到正确的LISTSIZE;但是我无法获得我的arrayList的任何元素。我总是得到“索引(0)”元素。我将非常感激的任何建议和帮助

+1

重复的http://stackoverflow.com/questions/2091465/how-do-i-pass-data-between-activities-in-android-application?rq=1 –

+1

可能的重复[如何传递数据在Android应用程序中的活动?](http://stackoverflow.com/questions/2091465/how-do-i-pass-data-between-activities-in-android-application) – Bobulous

+0

我想我能够开始意图和发送数据。因为我可以得到我的arrayList的大小。问题在于访问数据。 – Aybars

回答

1

您可以轻松地通过使用GSON

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

在Game.class

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

检查你的代码,以将数据添加到ArrayList的playerName。来自Intent的代码putStringArrayListExtra到Intent和getStringArrayListExtra是正确的。

相关问题