在Android开发中,有时候需要从一个Activity中传递数据到另一个Activity中,在Bundle中已经封装好了简单数据类型,例如String ,int ,float等。但是如果我们想要传递一个复杂的数据类型,比如一个Book对象,该怎么办呢?
        仔细的看了一下Bundle中的方法,其中有一个是putSerializable()方法,Serializable对象是一个可恢复对象接口,我们只需要让Book对象实现Serializable接口,就可以使用Bundle.putSerializable()方法传递Book对象了。废话不多说了,现将代码贴上:

 

 

 

Java代码  
  1. package com.bundletest.model.fneg;    
  2.   
  3. import java.io.Serializable;   
  4.   
  5. /**   
  6. *@Copyright:Copyright (c) 2008 - 2100   
  7. *@Company:Sagret  
  8. *@Author:fengcunhan fengcunhan@gmail.com   
  9. *@Package:com.bundletest.model.fneg   
  10. *@FileName:Book.java  
  11. *@Time:2010-12-19   
  12. *@User:feng  
  13. */  
  14. public class Book implements Serializable {   
  15. /**   
  16.  
  17. */  
  18. private static final long serialVersionUID = 1L;   
  19.   
  20. private String name;   
  21. private String id;   
  22. private String author;   
  23. public String getName() {   
  24. return name;   
  25. }   
  26. public void setName(String name) {   
  27. this.name = name;   
  28. }   
  29. public String getId() {   
  30. return id;   
  31. }   
  32. public void setId(String id) {   
  33. this.id = id;   
  34. }   
  35. public String getAuthor() {   
  36. return author;   
  37. }   
  38. public void setAuthor(String author) {   
  39. this.author = author;   
  40. }   
  41.   
  42. }  

 实例化Book类,得到Book对象book以及设置成员变量:

 

 

Java代码  
  1. if(TextUtils.isEmpty(bookName)||TextUtils.isEmpty(author)||TextUtils.isEmpty(id)){   
  2. Toast.makeText(AndroidBundleActivity.this"输入框不能为空", Toast.LENGTH_SHORT).show();   
  3. }else{   
  4. Book book=new Book();   
  5. book.setName(bookName);   
  6. book.setAuthor(author);   
  7. book.setId(id);   
  8. Intent intent=new Intent(AndroidBundleActivity.this,RecieveActivity.class);   
  9. Bundle bundle=new Bundle();   
  10. bundle.putSerializable("book", book);   
  11. intent.putExtras(bundle);   
  12. startActivity(intent);   
  13. }  

 在另一个Activity中获取传递过来的book对象,并显示:

 

 

Java代码  
  1. Intent intent=this.getIntent();   
  2. Bundle bundle=intent.getExtras();   
  3.   
  4. Book book=(Book)bundle.getSerializable("book");   
  5. nameText.setText("书名:"+book.getName());   
  6. authorText.setText("作者:"+book.getAuthor());   
  7. idText.setText("ID:"+book.getId());