How to send hashmap value to another activity using an intent

后端 未结 2 1103
暖寄归人
暖寄归人 2020-11-30 22:51

How to send HashMap value from one Intent to second Intent?

Also, how to retrieve that HashMap value in the second Activity?

相关标签:
2条回答
  • 2020-11-30 23:10

    Java's HashMap class extends the Serializable interface, which makes it easy to add it to an intent, using the Intent.putExtra(String, Serializable) method.

    In the activity/service/broadcast receiver that receives the intent, you then call Intent.getSerializableExtra(String) with the name that you used with putExtra.

    For example, when sending the 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);
    

    And then in the receiving 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"));
    }
    
    0 讨论(0)
  • 2020-11-30 23:13

    I hope this must work too.

    in the sending activity

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

    in the receiving activity

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

    when I am sending a HashMap like following,

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

    Hope it would help for someone.

    0 讨论(0)
提交回复
热议问题