通过实现Serializable接口
利用Java语言本身的特性,通过将数据序列化后,再将其传递出去。
实体类:
public class Person implements Serializable {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
1,设置参数
//1.通过Serializable接口传参数的例子
//HashMap<String,String> map2 = new HashMap<>();
//map2.put("key1", "value1");
//map2.put("key2", "value2");
//Bundle bundleSerializable = new Bundle();
//bundleSerializable.putSerializable("serializable", map2);
//Intent intentSerializable = new Intent();
//intentSerializable.putExtras(bundleSerializable);
//intentSerializable.setClass(MainActivity.this,
//SerializableActivity.class);
//startActivity(intentSerializable);
//2.通过Serializable接口传递实体类
Person person = new Person();
person.setAge(25);
person.setName("lyx");
Intent intent2 = new Intent(MainActivity.this, SerializableActivity.class);
intent2.putExtra("serializable", person);
startActivity(intent2);
2,接收参数
this.setTitle("Serializable例子");
//接收参数
//1.接收集合
// Bundle bundle = this.getIntent().getExtras();
//如果传 LinkedHashMap,则bundle.getSerializable转换时会报ClassCastException,不知道什么原因
//传HashMap倒没有问题。
//HashMap<String, String> map = (HashMap<String, String>) bundle.getSerializable("serializable");
//
//String sResult = "map.size() =" + map.size();
//
//Iterator iter = map.entrySet().iterator();
// while (iter.hasNext()) {
// Map.Entry entry = (Map.Entry) iter.next();
// Object key = entry.getKey();
// Object value = entry.getValue();
// //System.out.println("key---->"+ (String)key);
// //System.out.println("value---->"+ (String)value);
//
// sResult += "\r\n key----> " + (String) key;
// sResult += "\r\n value----> " + (String) value;
// }
//2.接收实体类
Person person = (Person) getIntent().getSerializableExtra("serializable");
String sResult = "姓名:" + person.getName() + "--年龄:" + person.getAge();
TextView tv = findViewById(R.id.tv);
tv.setText(sResult);