在Android上从bundle中检索数据时出现ClassCastException

在Android上从bundle中检索数据时出现ClassCastException,第1张

概述我有一些状态,我希望在片段的生命周期中保存.例如,当屏幕旋转时,它工作正常,但是当从磁盘中杀死并恢复进程时(我认为它是如何工作的),我得到一个ClassCastException. 这是一些代码: 初始化: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if 我有一些状态,我希望在片段的生命周期中保存.例如,当屏幕旋转时,它工作正常,但是当从磁盘中杀死并恢复进程时(我认为它是如何工作的),我得到一个ClassCastException.
这是一些代码:

初始化:

public voID onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    if (savedInstanceState == null) {        playListsMap = new linkedHashMap<Section,List<PlayList>>();    } else {        playListsMap = (linkedHashMap<Section,List<PlayList>>) savedInstanceState.getSerializable(PLAYListS_MAP_KEY);    }    setHasOptionsMenu(true);}

保存数据

@OverrIDepublic voID onSaveInstanceState(Bundle outState) {    if (isEverySectionsLoaded()) {        outState.putSerializable(PLAYListS_MAP_KEY,playListsMap);    } else {        outState.putSerializable(PLAYListS_MAP_KEY,new linkedHashMap<Section,List<PlayList>>());    }    // ...}

我从onCreate中的强制转换得到的例外:

04-10 01:06:43.430 E/AndroIDRuntime(28549): FATAL EXCEPTION: main04-10 01:06:43.430 E/AndroIDRuntime(28549): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mydomain.androID/com.mydomain.androID.ui.MainActivity}: java.lang.classCastException: java.util.HashMap cannot be cast to java.util.linkedHashMap

我知道在AndroID上使用parcelables会更好,但我仍然不明白这是怎么回事.

有任何想法吗?

解决方法 关于类似问题的有趣读物可以在 here找到

Any object that implements both java.util.List and java.io.Serializable will become
ArrayList after intent.putExtra(EXTRA_TAG,
suchObject)/startActivity(intent)/intent.getSerializableExtra(EXTRA_TAG).

我敢说同样重要的是实现可序列化和映射的任何东西. HashMap是您将获得的默认值.

围绕这个似乎是一个BUG的解决方案将类似于:

private linkedHashMap<Section,List<PlayList>> playListsMap;public voID onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    if (savedInstanceState == null) {        playListsMap = new linkedHashMap<Section,List<PlayList>>();    } else {        //assuming the BUG returns a hashmap        Map<Section,List<PlayList>> items = (Map<Section,List<PlayList>>) savedInstanceState.getSerializable(PLAYListS_MAP_KEY);        //this way you can ensure you are working with a linkedHashMap.         //for the rest off the application        playListsMap.putAll(items);    }    setHasOptionsMenu(true);}

上面的代码没有经过测试但应该可行.由于接口的使用,当错误得到修复时,此代码仍然有效.因此,当您的客户端获得AndroID更新时,您可以放心,您的代码应该仍然执行相同 *** 作,而不是崩溃和抱怨您无法将HashMap强制转换为linkedHashMap.

总结

以上是内存溢出为你收集整理的在Android上从bundle中检索数据时出现ClassCastException全部内容,希望文章能够帮你解决在Android上从bundle中检索数据时出现ClassCastException所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/web/1139032.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-31
下一篇2022-05-31

发表评论

登录后才能评论

评论列表(0条)

    保存