PutExtra treeMap returns HashMap cannot be applied to TreeMap android

I need your help, I do not understand what is happening?

I am trying to send a TreeMap between two actions, the code looks 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 that HashMap cannot be attributed to TreeMap. what

+7
source share
3 answers

As an alternative to @Jave suggestions, if you really need a data structure like TreeMap , just use the appropriate constructor, which takes another map as the data source. So, on the receiving side ( Two ), do the following:

 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 need to worry about a specific Map implementation. So instead, you can just go 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"); } } 
+2
source

It looks like it is being serialized in the HashMap and what you get. Guess you have to settle for a HashMap. Alternatively, you can create your own helper class and implement Parcelable, and then arrange the key / string sequence in order.

+1
source

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

 TreeMap<String, String> myMap = new TreeMap<String, String>; HashMap<String, String> receivedMap = getIntent().getExtras().get("map"); myMap.putAll(receivedMap); 
0
source

All Articles