android 使用Intent传递对象 Serializable 或者 Parcelabel 《第一行代码》

参考:《第一行代码》第13章

Android中Parcelable接口的使用:http://www.cnblogs.com/renqingping/archive/2012/10/25/Parcelable.html

#########################################################


使用Intent传递数据时,可以调用putExtra()方法实现。比如:

        Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
        intent.putExtra("String-data", "hello");
        intent.putExtra("int-data", 100);
        startActivity(intent);

从FirstActivity中传递到SecondActivity,在SecondActivity可以得到这些值:

        getIntent().getStringExtra("String-data");
        getIntent().getIntExtra("int-data", 0);


    /**
     * Add extended data to the intent.  The name must include a package
     * prefix, for example the app com.android.contacts would use names
     * like "com.android.contacts.ShowAll".
     *
     * @param name The name of the extra data, with package prefix.
     * @param value The CharSequence data value.
     *
     * @return Returns the same Intent object, for chaining multiple calls
     * into a single statement.
     *
     * @see #putExtras
     * @see #removeExtra
     * @see #getCharSequenceExtra(String)
     */
    public Intent putExtra(String name, CharSequence value) {
        if (mExtras == null) {
            mExtras = new Bundle();
        }
        mExtras.putCharSequence(name, value);
        return this;
    }

翻译:添加额外的数据到Intent。名字应该包含一个包前缀,举个例子,对于com.android.contacts来说应该使用名字像:"com.android.contacts.ShowAll"


不过putExtra()方法中仅支持一些常用的数据类型,当你想去传递一些自定义对象的时候就会发现无从下手。


有两种方式来使用Intent传递对象


###################################################################3


Serializable方式:


Serializable是序列化的意思,表示将一个对象转换成可存储或可传输的状态。序列化后的对象可以在网络上进行传输,也可以存储到本地。

序列化的方式很简单,只需要让一个对象取实现Serializable这个接口即可:


创建一个Person类,其中包含name和age这两个字段,想要将它序列化:

import java.io.Serializable;

/**
 * Created by root on 15-11-2.
 */
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;
    }
}

其中,get / set方法都是用于赋值和读取字段数据的,最重要的部分是在第一行。这里让Person类去实现了Serializable接口,这样所有的Person对象都是可序列化的。


        Person person = new Person();
        Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
        intent.putExtra("person_data", person);
        startActivity(intent);

创建一个Person实例,然后就直接将它传入putExtra()方法中

        Person person = (Person)getIntent().getSerializableExtra("person_data");

调用getSerializableExtra()方法来获取通过参数传递过来的序列化对象,接着将它向下转型成Person对象,这样就实现了使用Intent来传递对象的功能。


#####################################################


Parcelabel方式:

使用Parcelable也可以实现相同的效果,不过不同于将对象进行序列化,Parcelabel方式的实现原理是将一个完整的对象进行分解,而分解后的每一部分都是Intent所支持的数据类型,这样就实现了传递对象的功能。

重写Person类代码:

import android.os.Parcel;
import android.os.Parcelable;

/**
 * Created by root on 15-11-2.
 */
public class Person implements Parcelable {

    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;
    }

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(age);
    }
    
    public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {
       
        @Override
        public Person createFromParcel(Parcel source) {
            Person person=new Person();
            person.name = source.readString(); 
            person.age = source.readInt();
            return person;
        }

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

首先,让Person类去实现Parcelable接口,必须重写describeContents()和writeToParcel()这两个方法。其中describeContents()方法直接返回0就可以了,而writeToParcel()方法中需要调用Parcel的writeXxx()方法将Person类中的字段一一写出。注意字符串型数据就调用writeString(),整型数据就调用writeInt()方法,以此类推。

除此以外,必须在Person类中提供一个名为CREATOR的常量,在这里创建Parcelable.Creator接口的一个实现,并将泛型指定为Person。接着需要重写createFromParcel()和newArray()这两个方法,在createFromParcel()方法中我们要去读取刚才写出的name和age字段,并创建一个Person对象返回,其中name和age都是调用Parcel的readXxx()方法读取到的(注意:这里读取的顺序一定要和刚才写出的顺序完全相同)。而newArray()方法中的实现为,new出一个Person数组,并使用方法中传入的size作为数组大小即可。


接下来,在FirstActivity中仍然使用相同的代码来传递Person对象,在SecondActivity中获取对象的时候稍加改变:

        Person person = (Person)getIntent().getParcelableExtra("person_data");


#################################################################


Serializable的方式比较简单,但由于会把整个对象进行序列化,因此效率方面会比Parcelable方式低一些,所以在通常情况下,更加推荐使用Parcelable的方式来实现Intent传递对象的功能


转:http://my.oschina.net/zhoulc/blog/172163 : Android-Parcelable理解与使用(对象序列化)


Parcelable和Serializable的区别:

android自定义对象可序列化有两个选择:Serializable和Parcelable

一.对象为什么需要序列化

 1.永久性保存对象,保存对象的字节序列到本地文件

 2.通过序列化对象在网络中传递对象

 3.通过序列化对象在进程间传递对象

二.当对象需要被序列化时如何选择所使用的接口

 1.在使用内存的时候Parcelable比Serializable的性能高

 2.Serializable在序列化的时候会产生大量的临时变量,从而引起频繁的GC(内存回收)

 3.Parcelable不能使用在将对象存储在磁盘上的情况,因为在外界变化下Parcelable不能很好的保证数据的持续性


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值