9

I need your help, I cannot understand what's happening?

I'm trying to send a TreeMap between 2 activities, the code is something like this:

class One extends Activity{
 public void send(){
   Intent intent = new Intent(One.this, Two.class);
   TreeMap<String, String> map = new TreeMap<String, String>();
   map.put("1","something");
   intent.putExtra("map", map);
   startActivity(intent);
   finish();
 }
}

class Two extends Activity{
  public void get(){
  (TreeMap<String, String>) getIntent().getExtras().get("map");//Here is the problem
  }
}

This returns to me HashMap cannot be cast to TreeMap. What

user1893074
  • 103
  • 1
  • 3
  • For the gory details of what is happening, see my answer here: http://stackoverflow.com/questions/12300886/linkedlist-put-into-intent-extra-gets-recast-to-arraylist-when-retrieving-in-nex/12305459#12305459 – David Wasser Dec 19 '12 at 20:25

3 Answers3

3

As alternative to @Jave's suggestions, if you really need the data structure to be a TreeMap, just use the appropriate constructor that takes another map as data source. So on the receiving end (Two) do something like:

public class Two extends Activity {
    @Override public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TreeMap<String, String> map = new TreeMap<String, String>((Map<String, String>) getIntent().getExtras().get("map"));
    }
}

However, depending on your project, you probably don't have to worry about the exact Map implementation. So in stead, you could just cast to the Map interface:

public class Two extends Activity {
    @Override public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Map<String, String> map = (Map<String, String>) getIntent().getExtras().get("map");
    }
}
MH.
  • 45,303
  • 10
  • 103
  • 116
1

Sounds like it serializes to a HashMap and that's what you're getting. Guess you're gonna have to settle for a HashMap. Alternatively you can create your own helper class and implement Parcelable, then serialize the key/strings in order.

dmon
  • 30,048
  • 8
  • 87
  • 96
  • When you put anything that implements the `Map` interface into a `Bundle`, it comes out as a HashMap. Same with `List` - you always get an `ArrayList` out of it. See http://stackoverflow.com/questions/12300886/linkedlist-put-into-intent-extra-gets-recast-to-arraylist-when-retrieving-in-nex/12305459#12305459 – David Wasser Dec 19 '12 at 20:32
  • Cool, thanks for the explanation, I suspected something along this lines. It's good to know that a plain HashMap is supported, though. – dmon Dec 19 '12 at 21:46
0

Instead of casting the result directly to a TreeMap, you can create a new TreeMap<String, String> and use the putAll()-method:

TreeMap<String, String> myMap = new TreeMap<String, String>;
HashMap<String, String> receivedMap = getIntent().getExtras().get("map");
myMap.putAll(receivedMap);
Jave
  • 31,598
  • 14
  • 77
  • 90