Parcelable的用法及記錄一個Parcelable遇到的坑

大家都知道2個Act之前傳遞對象數據,一般就是用Serializable或者Parcelable了,好處我就不說了,肯定是Parcelable好用就對了
先看下數據對象

public class Person implements Parcelable {
    private String name;
    private int age;

    protected Person(Parcel in) {
        name = in.readString();
        age = in.readInt();
    }

    public static final Creator<Person> CREATOR = new Creator<Person>() {
        @Override
        public Person createFromParcel(Parcel in) {
            return new Person(in);
        }

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

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

    public static Creator<Person> getCREATOR() {
        return CREATOR;
    }

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

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

OK看下用法

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView mTvSvipPrice = findViewById(R.id.text);
        mTvSvipPrice.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        ArrayList<Person> objects = new ArrayList<>();

        Parcel parcel = Parcel.obtain();
        Person testPaciBean = new Person(parcel);
        testPaciBean.setAge(18);
        testPaciBean.setName("我是第一個");
        parcel.recycle();

        Person testPaciBean2 = new Person(parcel);
        testPaciBean2.setAge(20);
        testPaciBean2.setName("我是第二個");
        parcel.recycle();

        objects.add(testPaciBean);
        objects.add(testPaciBean2);
		//傳遞單獨對象
        Intent intent = new Intent(this, MainActivity2.class);
        intent.putExtra("JustBean", testPaciBean);
        //傳遞List對象  坑就在這裏了
        //正確方式 最簡單的方法
		intent.putParcelableArrayListExtra("JustList", objects);
		//坑在這裏  注意下面這一句是錯誤的        
        intent.putExtra("JustList", objects);
        //這樣寫也是錯誤的 
        startActivity(intent);
    }
}

主要注意2點,第一個不能直接putExtra應該用putParcelableArrayListExtra,還有一個問題,這個傳輸是有最大限制的,如果傳送的數據太大,我就把一個集合虧大10W唄,導致系統出錯 :java.lang.RuntimeException: Failure from system

最後看下接收方

//取單個對象
Person justBean = getIntent().getParcelableExtra("JustBean");
//取一個集合對象
ArrayList<Person> justList = getIntent().getParcelableArrayListExtra("JustList");
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章