0

I created a class called CardView. CardView object has 1 property: int number

I want to trasfer arrayList of CardView Objects from MainActivity to MainActivity2 I tried to do it but when I printed getNumber of the first(or any) object it returns 0 instead of the number I set in new Cardview(int number).

here is the code:

MainActivity onCreate():

List<CardView> list = new ArrayList<>();
    list.add(new CardView(10));
    list.add(new CardView(11));
    list.add(new CardView(12));
    Intent mIntent = new Intent(this, MainActivity2.class);
    mIntent.putParcelableArrayListExtra("Data", (ArrayList<? extends Parcelable>) list);
    startActivity(mIntent);

MainActivity2 onCreate():

List list;
    list = getIntent().getExtras().getParcelableArrayList("Data");
    Toast.makeText(this, ((CardView)list.get(0)).getNumber()+"", Toast.LENGTH_SHORT).show();

CardView Class:

public class CardView implements Parcelable {
    int number;
    public CardView(int number){
        this.number = number;
    }

    public int getNumber() {
        return number;
    }

    protected CardView(Parcel in) {
    }

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

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

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

    @Override
    public void writeToParcel(Parcel parcel, int i) {
    }
}

2 Answers 2

1

Try this:

protected CardView(Parcel in) {
    number = in.readInt();
}

@Override public void writeToParcel(Parcel parcel, int i) {    
    parcel.writeInt(number); 
} 

By default the value of uninitialized int variable will be 0, so initial value of number is 0. With this constructor number receive from parcel.

Sign up to request clarification or add additional context in comments.

3 Comments

Because of this line the app crash onCreate() of the second Activity
@Override public void writeToParcel(Parcel parcel, int i) { parcel.writeInt(number); }
I already understood it but really, Thank you! Please edit your answer so I can mark it as the correct answer
0

I figured it out with this video: https://www.youtube.com/watch?v=WBbsvqSu0is&ab_channel=CodinginFlow

I should add the following code to CardView class.

protected CardView(Parcel in) {
    number = in.readInt();
}

@Override
public void writeToParcel(Parcel parcel, int i) {
    parcel.writeInt(number);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.