0

I want to create and write data to a parcel. The reason i want to do the following is debugging. I want to write some concise code in one location which enable a certain flow in the application.

I want to modify this method to return an object which I create:

public MyMessage getMyMessage() {
        return myMessage;
}

MyMessage is a bean defined as:

@Bean
public class MyMessage implements Parcelable {

    @Optional
    private String message;

    public MyMessage() {
    }

    public MyMessage(Parcel in) {
        message = in.readString();
    }

    public String getMessage() {
        return message;
    }

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

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

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

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

}

I do not want to edit the MyMessage class and add a constructor or setter methods. MyMessage should stay exactly the same and I want to fill its messagefield by constructing a MyMessage object with a parcel.

I have tried this:

public MyMessage getMyMessage() {
    android.os.Parcel parcel = android.os.Parcel.obtain(); // TODO
    parcel.writeString("message is this");
    return MyMessage.CREATOR.createFromParcel(parcel);
    //return new MyMessage(parcel);
}

But the .writeString()does not seem to modify the parcel, the debugger detaches and i cannot step through it. The end result then is that the MyMessage bean has a null message. Where am I going wrong?

Adam
  • 2,845
  • 2
  • 32
  • 46

1 Answers1

1

Possible duplicate of Parcel write/read doesn't work in AndroidTestCase -why?:

One must reset the Parcel's data position with: parcel.setDataPosition(0);

activout.se
  • 6,058
  • 4
  • 27
  • 37