Activity传递对象的方法《转载》

http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0104/2256.html

这是一个针对技术开发者的一个应用,你可以在掘金上获取最新最优质的技术干货,不仅仅是Android知识、前端、后端以至于产品和设计都有涉猎,想成为全栈工程师的朋友不要错过!

Android中,Activity和Fragment之间传递对象,可以通过将对象序列化并存入Bundle或者Intent中进行传递,也可以将对象转化为JSON字符串,进行传递。

序列化对象可以使用Java的Serializable的接口、Parcelable接口。转化成JSON字符串,可以使用Gson等库。

1.Serializable
Model

public class Author implements Serializable{
    private int id;

    private String name;

    //...
}
public class Book implements Serializable{
    private String title;
    private Author author;
    //...
}

传递数据

  Book book=new Book(); 
  book.setTitle("Java编程思想"); 
  Author author=new Author(); 
  author.setId(1); 
  author.setName("Bruce Eckel"); 
  book.setAuthor(author); 
  Intent intent=new Intent(this,SecondActivity.class); 
  intent.putExtra("book",book); 
  startActivity(intent);

接受数据

 Book book= (Book) getIntent().getSerializableExtra("book");
 Log.d(TAG,"book title->"+book.getTitle());
 Log.d(TAG,"book author name->"+book.getAuthor().getName());



2.转化为JSON字符串

public class Author{
    private int id;

    private String name;

    //...
}
public class Book{
    private String title;
    private Author author;
    //...
}

发送数据

Book book=new Book();
book.setTitle("Java编程思想");
Author author=new Author();
author.setId(1);
author.setName("Bruce Eckel");
book.setAuthor(author);
Intent intent=new Intent(this,SecondActivity.class);
intent.putExtra("book",new Gson().toJson(book));
startActivity(intent);

接受数据

String bookJson=getIntent().getStringExtra("book");
Book book=new Gson().fromJson(bookJson,Book.class);
Log.d(TAG,"book title->"+book.getTitle());
Log.d(TAG,"book author name->"+book.getAuthor().getName());


3.使用Parcelable
实现Parcelable接口需要实现两个方法

describeContents方法。内容接口描述,默认返回0就可以;
writeToParcel方法。将传递的数据打包到Parcel容器中。

除了要实现这两个方法还必须创建一个Parcelable.Creator接口的实例,用于读取Parcel容器中的数据

Model

public class Author implements Parcelable{
    private int id;

    private String name;

    //setter & getter...

    @Override
    public int describeContents() {

        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        //该方法将类的数据写入外部提供的Parcel中.即打包需要传递的数据到Parcel容器保存,
        // 以便从parcel容器获取数据
        dest.writeString(name);
        dest.writeInt(id);

    }
    public static final Creator<Author> CREATOR=new Creator<Author>() {
        @Override
        public Author createFromParcel(Parcel source) {
            //从Parcel容器中读取传递数据值,封装成Parcelable对象返回逻辑层。
            Author author=new Author();
            author.setName(source.readString());
            author.setId(source.readInt());
            return author;
        }

        @Override
        public Author[] newArray(int size) {
            //创建一个类型为T,长度为size的数组,仅一句话(return new T[size])即可。方法是供外部类反序列化本类数组使用。
            return new Author[size];
        }
    };
}
public class Book implements Parcelable{
    private String title;
    private Author author;
    //setter & getter...

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(title);
        dest.writeParcelable(author,flags);
    }
    public static final Creator<Book> CREATOR=new Creator<Book>() {
        @Override
        public Book createFromParcel(Parcel source) {
            Book book=new Book();
            book.setTitle(source.readString());
            book.setAuthor(source.<Author>readParcelable(Author.class.getClassLoader()));
            return book;
        }

        @Override
        public Book[] newArray(int size) {
            return new Book[0];
        }
    };
}

传递数据

Book book=new Book();
book.setTitle("Java编程思想");
Author author=new Author();
author.setId(1);
author.setName("Bruce Eckel");
book.setAuthor(author);
Intent intent=new Intent(this,SecondActivity.class);
intent.putExtra("book",book);
startActivity(intent);

接受数据

Book book=getIntent().getParcelableExtra("book");
Log.d(TAG,"book title->"+book.getTitle());
Log.d(TAG,"book author name->"+book.getAuthor().getName());

==============================================

Intent intent =new Intent(CurrentActivity.this,OtherActivity.class);
  // 创建一个带“收件人地址”的 email 
 Bundle bundle =new Bundle();// 创建 email 内容
 bundle.putBoolean("boolean_key", true);// 编写内容
 bundle.putString("string_key", "string_value"); 
 intent.putExtra("key", bundle);// 封装 email 
 startActivity(intent);// 启动新的 Activity 

那么“收件人”该如何收信呢?在 OtherActivity 类的 onCreate() 或者其它任何地方使用下面的代码就可以打开这封“e-mail”阅读其中的信息:
 Intent intent =getIntent();// 收取 email 
 Bundle bundle =intent.getBundleExtra("key");// 打开 email 
 bundle.getBoolean("boolean_key");// 读取内容
 bundle.getString("string_key"); 

上面我们通过 bundle 对象来传递信息,bundle 维护了一个 HashMap<String, Object> 对象,将我们的数据存贮在这个 HashMap 中来进行传递。但是像上面这样的代码稍显复杂,因为 Intent 内部为我们准备好了一个 bundle ,所以我们也可以使用这种更为简便的方法:
 Intent intent =new Intent(EX06.this,OtherActivity.class); 
 intent.putExtra("boolean_key", true); 
 intent.putExtra("string_key", "string_value"); 
 startActivity(intent); 

接收:
 Intent intent=getIntent(); 
 intent.getBooleanExtra("boolean_key",false); 
 intent.getStringExtra("string_key"); 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值