Sending LinkedHashMap to intent
Asked Answered
M

3

6

I want send LinkedHashMap to another Intent. But I don't known what method for extras is allowable.

Bundle extras = getIntent().getExtras();
  LinkedHashMap<Integer, String[]> listItems = extras.get(LIST_TXT);
Mediant answered 12/11, 2010 at 11:16 Comment(0)
A
6

You cannot reliably send a LinkedHashMap as an Intent extra. When you call putExtra() with a LinkedHashMap, Android sees that the object implements the Map interface, so it serializes the name/value pairs into the extras Bundle in the Intent. When you want to extract it on the other side, what you get is a HashMap, not a LinkedHashMap. Unfortunately, this HashMap that you get has lost the ordering that was the reason you wanted to use a LinkedHashMap in the first place.

The only reliable way to do this is to convert the LinkedHashMap to an ordered array, put the array into the Intent, extract the array from the Intent on the receiving end, and then recreate the LinkedHashMap.

See my answer to this question for more gory details.

Afoot answered 15/8, 2016 at 18:24 Comment(0)
B
0

The best way is to convert it to ArrayList of the same type
examble :

 LinkedHashSet<Long> uniqueIds = new LinkedHashSet();
 ArrayList<Long> ids = new ArrayList(uniqueIds);
    
 Intent intent = new Intent(getContext(), UserStoryActivity.class);
 intent.putParcelableArrayListExtra(FLAG_USERS_STORY_LIST_IDS, (ArrayList) ids);
 startActivity(intent);
Blueweed answered 25/8, 2020 at 7:59 Comment(0)
S
0

Thanks @David Wasser for pointing out this issue.

I have another approach is to use Gson to parse your whatever map to json string, then put into the intent. Less drama!

Code send:

gson.toJson(data)

Code get back:

Kotlin:

gson.fromJson<LinkedHashMap<Int, Int>>(
                    it.getStringExtra(ARG_DATA),
                    object : TypeToken<LinkedHashMap<Int, Int>>() {}.type
                )

Java:

gson.fromJson(
     it.getStringExtra(ARG_DATA),
     new TypeToken<ArrayList<Mountain>>(){}.getType()
);
Sandhurst answered 3/11, 2021 at 10:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.