Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - How to pass HashMap<String,String> between activities?

How to pass the detail HashMap to another Activity?

HashMap<String,String> detail = new HashMap<String, String>();
detail.add("name","paresh");
detail.add("surname","mayani");
detail.add("phone","99999");
......
......
like image 899
Paresh Mayani Avatar asked Feb 14 '11 12:02

Paresh Mayani


4 Answers

This is pretty simple, All Collections objects implement Serializable (sp?) interface which means they can be passed as Extras inside Intent

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.

like image 198
st0le Avatar answered Oct 13 '22 21:10

st0le


Solution:

Sender Activity:

HashMap<String, String> hashMap= adapter.getItem(position);
Intent intent = new Intent(SourceActivity.this, DestinationActivity.class);
intent.putExtra("hashMap", hashMap);
startActivity(intent);

Receiver Activity:

Intent intent = getIntent();    
HashMap<String, String> hashMap = (HashMap<String, String>) intent.getSerializableExtra("hashMap");
like image 39
Paresh Mayani Avatar answered Oct 13 '22 21:10

Paresh Mayani


i used this to pass my HashMap

startActivity(new Intent(currentClass.this,toOpenClass.class).putExtra("hashMapKey", HashMapVariable));

and on the receiving activity write

HashMap<String,String> hm = (HashMap<String,String>) getIntent().getExtras().get("hashMapKey");

cuz i know my hashmap contains string as value.

like image 4
MetaSnarf Avatar answered Oct 13 '22 21:10

MetaSnarf


An alternative is if the information is something that might be considered "global" to the application, to then use the Application class. You simply extend it and then define your custom class in your manifest using the <application> tag. Use this sparingly, though. The urge to abuse it is high.

like image 1
MattC Avatar answered Oct 13 '22 22:10

MattC