3

I stuff a TreeMap into an intent:

private TreeMap<Long, Long> mSelectedItems;

...

mSelectedItems = new TreeMap<Long, Long>();

...

Intent intent = new Intent();
intent.putExtra("results", mSelectedItems);

setResult(RESULT_OK, intent);

and then attempt to read it back out in the calling activity:

TreeMap<Long, Long> results = (TreeMap<Long, Long>)
    data.getSerializableExtra("results");

which causes:

E/AndroidRuntime(26868): Caused by: java.lang.ClassCastException: java.util.HashMap cannot be cast to java.util.TreeMap

Well, sure, but since I'm not using HashMap anywhere in the code, and since TreeMap implements Serializable, this should work without error, no? Why is android trying to force a class on me that I'm not using?

tbm
  • 1,142
  • 12
  • 22
  • 1
    Have you even tried searching for a solution? [link](http://stackoverflow.com/questions/13960153/putextra-treemap-returns-hashmap-cannot-be-cast-to-treemap-android), [link](http://stackoverflow.com/questions/12300886/linkedlist-put-into-intent-extra-gets-recast-to-arraylist-when-retrieving-in-nex/12305459#12305459) – Emmanuel Apr 04 '14 at 15:59
  • Actually I did, but apparently I didn't use the correct search terms. The first link doesn't mention ClassCastException, and the second doesn't mention either kind of Map. – tbm Apr 04 '14 at 16:04

1 Answers1

6

The first link that Emmanuel provided is the exact same issue you are having. It doesn't specifically mention that exact error but it is implied.

The issue is that when your TreeMap is serialized it will come back as a HashMap. Completely explained by this answer which Emmanuel also provided.

So simply doing the follow shall resolve your issue:

TreeMap<Long, Long> results = new TreeMap<Long, Long>((HashMap<Long, Long>) getIntent().getSerializableExtra("results"));

Basically populates your results TreeMap with the HashMap returned from the bundle.

Also upvote those answers in the links provided if this resolves your issue.

Community
  • 1
  • 1
singularhum
  • 5,072
  • 2
  • 24
  • 32
  • Regardless, neither link was returned in either a google search or as a suggested possible question when I added this one. I've upvoted the answers provided since they did resolve the issue. – tbm Apr 05 '14 at 17:10
  • @tbm Oh I see. That happens sometimes, you search for something but can't find it although there is something. Anyway, since it resolved your issue please accept answer (instead of mentioning as a comment). Glad it worked out for you in the end. – singularhum Apr 05 '14 at 17:16