0

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

这是我serialized通过实现拥有的 Bean 类Parceble

客户类

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
4

1 回答 1

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可以为您提供很好的参考。

于 2013-05-15T06:45:27.100 回答