- public class SerializableBook implements Serializable {
- private static final long serialVersionUID = 4226755799531293257L;
- private String Name;
- private String Author;
- private String Pubdate;
- private float Price;
- public void setName(String name) {
- Name = name;
- }
- public String getName() {
- return Name;
- }
- public void setAuthor(String author) {
- Author = author;
- }
- public String getAuthor() {
- return Author;
- }
- public void setPubdate(String pubdate) {
- Pubdate = pubdate;
- }
- public String getPubdate() {
- return Pubdate;
- }
- public void setPrice(float price) {
- Price = price;
- }
- public float getPrice() {
- return Price;
- }
- }
然后起一个Activity A,这都是和之前的Activity介绍的例子一样,代码如下:
Java代码
- public class ActivityA extends Activity {
- private String SerializableKey = "ourunix_serialzable";
- private Button mButton;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.layout_for_a);
- initView();
- mButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- tranSerializableObject();
- }
- });
- }
- public void initView(){
- mButton = (Button) findViewById(R.id.a_button);
- mButton.setText("A跳B");
- }
- public void tranSerializableObject(){
- Intent in = new Intent();
- in.setClass(ActivityA.this, ActivityB.class);
- //实例化一个SerializableBook对象
- SerializableBook book = new SerializableBook();
- book.setAuthor("walfred");
- book.setName("How to learn Android");
- book.setPrice(10.00f);
- book.setPubdate("2014-01-01");
- Bundle extras = new Bundle();
- extras.putSerializable(SerializableKey, book);
- in.putExtras(extras);
- startActivity(in);
- }
- }
最后在Activity B中接受这个对象,并展示出来,代码如下:
Java代码
- public class ActivityB extends Activity {
- private String SerializableKey = "ourunix_serialzable";
- private TextView mTextView;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- setContentView(R.layout.layout_for_b);
- initView();
- getAndShowSerialzableObeject();
- }
- public void initView(){
- mTextView = (TextView)findViewById(R.id.b_textview);
- }
- public void getAndShowSerialzableObeject(){
- Bundle extras = getIntent().getExtras();
- if (extras != null){
- SerializableBook book = (SerializableBook) extras.get(SerializableKey);
- mTextView.setText("Name:" + book.getName()+"\n"
- + "Author:" + book.getAuthor() + "\n"
- + "Pubdate:" + book.getPubdate() + "\n"
- + "Price:" + book.getPrice());
- }else{
- mTextView.setText("nothing");
- }
- }
- }