Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send hashmap value to another activity using an intent

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

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

like image 488
Piyush Avatar asked Sep 28 '11 04:09

Piyush


People also ask

How do you pass a HashMap from one activity to another?

Use putExtra(String key, Serializable obj) to insert the HashMap and on the other Activity use getIntent(). getSerializableExtra(String key) , You will need to Cast the return value as a HashMap though.

How to put HashMap in intent Android?

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

What is the putExtra () method used with intent for?

putExtra() method is used for send the data, data in key-value pair key is variable name and value can be Int, String, Float etc.

What is intent putExtra?

Intents are asynchronous messages which allow Android components to request functionality from other components of the Android system. For example an Activity can send an Intents to the Android system which starts another Activity . putExtra() adds extended data to the intent.


2 Answers

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")); } 
like image 196
JesusFreke Avatar answered Sep 27 '22 22:09

JesusFreke


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.

like image 28
Janitha Prabath Madushanka Avatar answered Sep 27 '22 22:09

Janitha Prabath Madushanka