使用Parcelable在活动之间进行通信

时间:2013-05-15 06:41:35

标签: android

所以我试图使用android中提供的Parceble将我的对象从一个活动传递到另一个活动,因为在这种情况下使用它是正确的。

这是我的Bean类,我通过实现serialized

Parceble

Customer.class

public class Customer implements Parcelable {

    int a;
    String name;

    public Customer(int ab , String n) {
    this.a=ab;
    this.name=n;
    }

    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


    public Customer(Parcel in) {
         a= in.readInt();   
         name= in.readString();
        //readFromParcel(in);
    }

    @Override
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(a);
    }

    public static final Parcelable.Creator<Customer> CREATOR= new Parcelable.Creator<Customer>() {

        @Override
        public Customer createFromParcel(Parcel source) {
            return new Customer(source);
        }

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


    private void readFromParcel(Parcel in) {

        a= in.readInt();    
        name= in.readString();
   }
}

MainActivity.class

public class MainActivity extends Activity {

    Button b;
    Customer c;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        b=(Button) findViewById(R.id.button1);

        c=new Customer(33,"nn");

        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent i=new Intent(MainActivity.this,CustomActivity.class);
                i.putExtra("myobj", c);
                startActivity(i);
            }
        });
    }

}

CustomActivity.class

public class CustomActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent it=getIntent();
        Customer c=(Customer)it.getParcelableExtra("myobj");

        System.out.println("and object is "+c.getA()+"/"+c.getName());
    }
}

这是我在Logcat中的输出:

05-15 12:02:56.014: I/System.out(25581): and object is 2/null

1 个答案:

答案 0 :(得分:3)

问题出在您的readFromParcel方法中。规则是“ 成员序列在编写或阅读Parcelable对象的成员时必须相同

所以你必须从

更改readFromParcel(Parcel in)
private void readFromParcel(Parcel in) {    
        a= in.readInt();    
        name= in.readString();
   }

private void readFromParcel(Parcel in) {              
        name= in.readString();
       a= in.readInt();  
   }

因为您的writeToParcel(..)先写name然后a

PARCELABLE INTERFACE OVERVIEW可以为您提供良好的参考。