序列化后的对象可以在网络上进行传输,也可以存到本地。
序列化的方法很简单只要让一个类去实现Serializable接口就可以了。
下面是个例子:
Person 是个javabeen
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;
}
}
MainActivity中传递对象
public class MainActivity extends Activity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//传递序列化后的对象
Person person=new Person();
person.setName("Tom");
person.setAge(1);
Intent intent =new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("person", person);
startActivity(intent);
}
});
}
}
SecondActivity 中接收对象
public class SecondActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
/*
* 这里调用了getSerializableExtra();方法来获取通过参数传递过来的序列化对象,
* 接着再将它向下转型成person对象,
* 这样我们就实现了使用Intent来传递对象的功能了
*
*/
Intent intent = getIntent();
Person person = (Person) intent.getSerializableExtra("person");
Log.e("1", "person对象"+person);
Log.e("1", "person名字"+person.getName());
Log.e("1", "person年龄"+person.getAge());
}
}//class
如果没有明白下载我的例子
http://download.csdn.net/detail/zhaihaohao1/8407553