在String中将字符串数组的ArrayList从一个活动传递到另一个活动

我想在Android中将字符串数组的ArrayList从一个活动传递到另一个活动。
我如何使用intentbundle ? 请考虑在这种情况下, intent.putStringArrayListExtra不起作用,因为它不适用于字符串数组。

不确定你的意思是“字符串数组的ArrayList”

如果您有字符串数组,请检查以下链接

在android活动之间传递字符串数组

http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

ArrayList实现Serializable

你可以使用意图

  ArrayList mylist = new ArrayList(); Intent intent = new Intent(ActivityName.this, Second.class); intent.putStringArrayListExtra("key", mylist); startActivity(intent); 

要检索

  Intent i = getIntent(); ArrayList list = i.getStringArrayListExtra("key"); 

public Intent putStringArrayListExtra (String name, ArrayList value)

将扩展数据添加到intent。 名称必须包含包前缀,例如app com.android.contacts将使用“com.android.contacts.ShowAll”之类的名称。

参数

 name The name of the extra data, with package prefix. value The ArrayList data value. 

返回

 Returns the same Intent object, for chaining multiple calls into a single statement. 

传递String数组的ArrayList

 String[] people = { "Mike Strong", "Jennifer Anniston", "Tom Bennet", "Leander Paes", "Liam Nesson", "George Clooney", "Barack Obama", "Steve Jobs", "Larry Page", "Sergey Brin", "Steve Wozniak" }; String[] people1 = { "raghu", "hello" }; ArrayList list = new ArrayList(); list.add(people); list.add(people1); Intent i = new Intent(MainActivity.this,SecondActivity.class); i.putExtra("key", list); startActivity(i); 

要检索

 Intent in = getIntent(); ArrayList list =(ArrayList) in.getSerializableExtra("key"); for(int i=0;i 

我不熟悉这是否可行,因为Bundle类的情况如此,所以我将实现一个自定义对象来容纳您的ArrayList。 这是一个很好的清洁解决方案,可以容纳您在两个活动中都需要访问的其他常见数据

 public class MyCustomData implements Serializable { static final long serialVersionUID = 42432432L; public ArrayList strings = new ArrayList(); public MyCustomData() { }; } 

然后在你的活动中:

 MyCustomData myCustomDataInstance = new MyCustomData(); myCustomDataInstance.strings = //set it here; Bundle bundle = new Bundle(); Intent selectedIntent = new Intent(getActivity(), MyNextClass.class); bundle.putSerializable("key", myCustomDataInstance); selectedIntent.putExtras(bundle); startActivity(selectedIntent); 

我也建议使用arraylists的arraylist而不是数组的arraylist

所以你想要传递一个String数组列表,而不是一个字符串列表,对吧? 由于ArrayList是可序列化的,因此您可以非常轻松地添加它:

 ArrayList list = new ArrayList(); // Add some String[] Intent i = new Intent(); i.putExtra("xxx", list); // And to get it back ArrayList list = (ArrayList) i.getSerializableExtra("xxx"); 

这个问题有一个简单的解决方案,您只需在First活动中声明ArrayList public&static,然后在另一个活动中调用它。

在您的第一个活动中

 public static ArrayList myList = new ArrayList(); myList.add("some_value"); 

在第二个活动中

 Toast.makeText(getApplicationContext(),FirstActivity.myList.size().toString(),Toast.LENGTH_SHORT).show();