SamuelPS
SamuelPS

Reputation: 555

Hashmap as param for a Fragment

I have a fragment with an ExpandableList which content is provided by a HashMap<String,List<String>>. This HashMap<String,List<String>> is filled in Fragment's Activity and i need to pass it to the fragment.

To do it, i was planning to do a Fragment transaction but i found the problem:

In the method "newInstance" of the fragment, when setting arguments to the Bundle, there is no method to put a HashMap.

Ex:

Bundle args = new Bundle();
args.putInt(ARG_PARAM1,index); //method .putHashmap doesn't exist.

So, how can i pass my hashmap in bundle to the Fragment? Please provide an solution for this one.Thanks in advance

Upvotes: 4

Views: 7911

Answers (2)

Rohit5k2
Rohit5k2

Reputation: 18112

To pass HashMap do this

MyFragment fr = new MyFragment(); // Replace with your Fragment class
Bundle bundle = new Bundle();
bundle.putSerializable("hashmap",mMap);
fr.setArguments(bundle);

To retrieve do this

HashMap<String,List<String>> mMap = new HashMap<String,List<String>>();
Bundle b = this.getArguments();
if(b.getSerializable("hashmap") != null)
   mMap = (HashMap<String,List<String>>)b.getSerializable("hashmap");

Upvotes: 20

pelotasplus
pelotasplus

Reputation: 10052

Try using:

Bundle args = new Bundle();
args.putSerializable(ARG_PARAM1, hereGoesYourHashMap);

as according to the docs:

https://developer.android.com/reference/java/util/HashMap.html

HashMap is Serializable

Upvotes: 4

Related Questions