2012-12-19 105 views
7

我需要你的帮助,我不明白发生了什么?putExtra treeMap返回HashMap不能转换为TreeMap android

我想送2个活动之间一个TreeMap,代码是这样的:

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 
    } 
} 

这将返回到我的HashMap不能被转换为TreeMap的。什么

+0

对于所发生的事情的血淋淋的细节,请参阅我的答案在这里:http://stackoverflow.com/questions/12300886/linkedlist-put-into -intent-extra-gets-recast-to-arraylist -in-retrieval -in-nex/12305459#12305459 –

回答

2

作为替代@ java的的建议,如果你真的需要的数据结构是一个TreeMap,只需使用其他地图作为数据源的适当构造函数。所以在接收端(Two)做这样的事情:

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")); 
    } 
} 

但是,根据你的项目,你可能不担心确切Map实施。因此,在代替,你可以只投给Map接口:

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"); 
    } 
} 
1

听起来像它序列化到一个HashMap,这就是你得到的。猜猜你必须要解决一个HashMap。或者,您可以创建自己的助手类并实现Parcelable,然后按顺序序列化键/字符串。

+0

当你将任何实现了Map接口的东西放到一个Bundle中时,它就会以HashMap的形式出现。与'List'一样 - 你总是从中得到一个'ArrayList'。请参阅http://stackoverflow.com/questions/12300886/linkedlist-put-int-intent-extra-gets-recast-to-arraylist-when-retrieving-in-nex/12305459#12305459 –

+0

很酷,感谢您的解释,我怀疑这一点。尽管知道支持一个普通的HashMap是很好的。 – dmon

0

而是直接铸造结果为TreeMap,你可以创建一个新TreeMap<String, String>和使用putAll() - 方法:

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