我有一个Hashmap,我想传递给下一个Activity,所有答案都显示这个方法 - :
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);
但它表示无法解决方法
答案 0 :(得分:1)
试试这个
// 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")+"");
}
}
答案 1 :(得分:0)
尝试此操作来传输您的值,对象必须是可序列化的,根据您的要求更改参数。
HashMap<String, Boolean> hashMap = new HashMap<String, Boolean>();
hashMap.put("key", "value");
Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("map", (Serializable)hashMap);
startActivity(intent);
并在NextActivity
获取数据,请尝试使用
Intent intent = getIntent();
HashMap<String, Boolean> hashMap = (HashMap<String, Boolean>)intent.getSerializableExtra("map");
Log.v("HashMapTest", hashMap.get("key"));
检查是否
Boolean b= hashMap.get("key");
if(b==true){
//Your Toast Message
}
试试这个,让我知道它是否适合你。
答案 2 :(得分:0)
尝试使用singleton类使用setter方法存储hashmap,并使用getter方法在其他活动上获取它。
答案 3 :(得分:0)
这是我尝试并且工作 - : //添加数据
Intent ActivityIntent = new Intent(MainActivity.this, NewActivity.class);
Bundle bundles = new Bundle();
bundles.putSerializable("myMap", (Serializable) myMap);
ActivityIntent.putExtra("bundle",bundles);
//提取数据
Bundle bundle = getIntent().getBundleExtra("bundle");
HashMap<String, Boolean> myMap = (HashMap<String, Boolean>) bundle.getSerializable("myMap");
if(myMap.get(StringOfItemWhichIsTrue)) {
Toast.makeText(this, "Works", Toast.LENGTH_SHORT).show();
}