首页 > 解决方案 > 使用 Serializable 方法将 HashMap(String,Boolean) 传递给 nextActivity-Android

问题描述

我有一个要传递给下一个活动的 Hashmap,所有答案都显示此方法-:

Intent intent=new Intent(MainActivity.this,NextActivity.class);
Bundle extras = new Bundle();
extras.putSerializable("YourHashMap",hashMap);
intent.putExtras(extras);
startActivity(intent);

但它显示了错误的第二个参数,它需要 Serializable 而不是 Map String,Boolean>

我什至给了这个基本的尝试-:

intent.putExtra("myMap",myMap);

但它说它无法解决方法

标签: androidandroid-intentserializationhashmap

解决方案


试试这个

 // pass HashMap from one Activity
                Intent intent = new Intent(this, AboutActivity.class);

                HashMap<String, Boolean> map = new HashMap<>();
                map.put("var",true);
                Bundle bun = new Bundle();
                bun.putSerializable("map", map);
                intent.putExtra("bundle",bun);

                startActivity(intent);
                overridePendingTransition(R.anim.slide_from_right, R.anim.nothing);


                // get HashMap from another activity
                Bundle  bundle = getIntent().getBundleExtra("bundle");
                if(bundle != null){
                    HashMap<String,Boolean> map = (HashMap<String, Boolean>) bundle.getSerializable("map");
                    if(map != null){
                        Log.e("bundle",map.get("var")+"");
                    }

                }

推荐阅读