【问题标题】:How to send hashmap value to another activity using an intent如何使用意图将哈希图值发送到另一个活动
【发布时间】:2011-11-26 13:16:51
【问题描述】:

如何将HashMap 值从一个 Intent 发送到第二个 Intent?

另外,如何在第二个 Activity 中检索 HashMap 值?

【问题讨论】:

  • 嗨,您发送的是哪个值(int, string,double..)?
  • 表示我要发送的字符串值
  • @Piyush.. 另外 JesusFreke 的回答这样做是为了获取值,String[] val = new String[hashMap.size]; (hasMap.values).toArray(val);
  • 我们不能通过intent直接发送hash map。对于替代创建两个数组列表,一个是保存键,另一个是保存值。现在通过意图发送这两个数组列表,在另一个类中,您将获得两个数组列表,现在创建一个空的 Hashmap 并添加键、值。要获取键和值循环,您的键数组列表对应的键从值数组列表中获取值。

标签: android hashmap


【解决方案1】:

Java 的 HashMap 类扩展了Serializable 接口,这使得使用Intent.putExtra(String, Serializable) 方法将其添加到意图变得很容易。

在接收到意图的活动/服务/广播接收器中,然后调用 Intent.getSerializableExtra(String) 与您在 putExtra 中使用的名称。

例如发送intent时:

HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("key", "value");
Intent intent = new Intent(this, MyOtherActivity.class);
intent.putExtra("map", hashMap);
startActivity(intent);

然后在接收Activity中:

protected void onCreate(Bundle bundle) {
    super.onCreate(savedInstanceState);

    Intent intent = getIntent();
    HashMap<String, String> hashMap = (HashMap<String, String>)intent.getSerializableExtra("map");
    Log.v("HashMapTest", hashMap.get("key"));
}

【讨论】:

  • 请注意 HashMap 是序列化的。显然,地图不会。
  • Map 是一个接口——你不能序列化一个接口,只能序列化它的一个特定实现。在这种情况下,Map 本身并没有实现/扩展 Serializable 接口,所以它是否要实现 Serializable 取决于具体的实现。 HashMap 确实实现了它。
  • 嗨,我正在发送一个 HashMap 作为我为另一个活动的结果而启动的活动的可序列化额外内容。所以我要返回结果的意图。当我尝试从意图中检索 HashMap 时, (HashMap)intent.getSerializableExtra("map");返回空值。是因为我正在使用 HashMap 还是因为我从一个为另一个 Activity 的结果创建的 Activity 发送它?
  • @marienke 我在我的项目中以这种方式使用了 HashMap 并且效果很好。我猜你的问题可能是后一个,祝你好运。
  • 我这样收到演员表警告
【解决方案2】:

我希望这也可以工作。

在发送活动中

Intent intent = new Intent(Banks.this, Cards.class);
intent.putExtra("selectedBanksAndAllCards", (Serializable) selectedBanksAndAllCards);
startActivityForResult(intent, 50000);

在接收活动中

Intent intent = getIntent();
HashMap<String, ArrayList<String>> hashMap = (HashMap<String, ArrayList<String>>) intent.getSerializableExtra("selectedBanksAndAllCards");

当我发送如下 HashMap 时,

Map<String, ArrayList<String>> selectedBanksAndAllCards = new HashMap<>();

希望对某人有所帮助。

【讨论】:

    猜你喜欢
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多