如何使用intent将hashmap值发送到另一个活动

时间:2011-09-28 04:15:16

标签: android hashmap

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

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

2 个答案:

答案 0 :(得分:177)

Java的HashMap类扩展了Serializable接口,可以使用Intent.putExtra(String, Serializable)方法将其添加到intent中。

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

例如,发送意图时:

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

然后在接收活动中:

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"));
}

答案 1 :(得分:4)

我希望这也必须奏效。

发送活动

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

希望这会对某人有所帮助。