【问题标题】:issue to pass arraylist from an intent to another将arraylist从一个意图传递给另一个的问题
【发布时间】:2015-12-04 22:43:57
【问题描述】:

在问这里之前,我首先搜索如何将一个数组列表从一个意图传递给另一个。感谢在 SO 上发表的一篇文章,我想我找到了一种方法。

问题是,当我尝试显示目标活动的数组列表中的元素时,我只得到了我最初在离开活动中拥有的众多元素之一。

明确地说,这是我第一次活动中的代码:

HashMap map = new HashMap<String,String>();

map.put("key1","value1");
map.put("key2","value2");

arrayList.add(map);
Log.d("arrayList", String.valueOf(arrayList));

在 logcat 中,我有预期的元素:

D/arrayList:: [{"key1":"value1"},{"key2","value2"}

然后,我用这个来追求:

Intent intent = new Intent(MyFirstActivity.this,MySecondActivity.class);
intent.putExtra("arrayList",arrayList);

现在,这是我的第二个活动应该是接收到的元素。

Intent intent = getIntent();
arrayList = (ArrayList<HashMap<String,String>>) getIntent().getSerializableExtra("arrayList");
Log.d("arraySecondActivity", String.valueOf(arrayList));

在logcat中,只有我的第二项是显示:

D/arraySecondActivity: [{key2=value2}]

我不知道为什么……有人可能知道吗?

谢谢!

【问题讨论】:

  • 确保您的项目在通过意图传递之前已添加到您的数组列表中
  • 怎么样?我的意思是,为什么我的第二个可以,而第一个不行?

标签: android android-intent arraylist hashmap


【解决方案1】:

intent.putExtra("arrayList",arrayList); 你的代码有这个错误。 在传递之前可序列化数组列表,如下所示

试试这个代码

 ArrayList<Object> object = new ArrayList<Object>();
 Intent intent = new Intent(Current.class, next.class);
 Bundle args = new Bundle();
 args.putSerializable("ARRAYLIST",(Serializable)object);
 intent.putExtra("BUNDLE",args);
 startActivity(intent);

在下一个类中

 Intent intent = getIntent();
 Bundle args = intent.getBundleExtra("BUNDLE");
 ArrayList<Object> object = (ArrayList<Object>)  args.getSerializable("ARRAYLIST");

【讨论】:

  • 它也不起作用。我得到了和以前一样的结果。
  • 确保您的项目已添加到您的数组列表中
  • 在我的第一个活动中,我确保我的两个项目通过 logcat 出现在我的数组列表中,因为我认为有问题......但是我的两个项目显示在那里......我的主要问题我不明白为什么我的第二个项目在我的第二个活动中很好地显示,而我的第一个则不是......
【解决方案2】:

假设 strinclude 是一个简单的整数数组列表。

ArrayList<Integer> strinclude=new ArrayList<Integer>();

活动 1:

//Here I am sending the arraylist to Activity2
 Intent i=new Intent(MainActivity.this,ResultActivity.class);
 i.putExtra("include",strinclude);
startActivity(i);

活动 2:

  //Here I am recieving the arraylist from Activity1
ArrayList<Integer> strinclude=new ArrayList<Integer>();
strinclude=(ArrayList<Integer>) getIntent().getSerializableExtra("include");

就是这样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-06
    • 2013-12-10
    • 2014-07-24
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    • 2015-07-11
    相关资源
    最近更新 更多