Java – Parcelable works without proper implementation

In the Android application, I send a bundle from an activity to a fragment

public class Bar implements Parcelable {

private Map<String, String> hash;
private int id;

protected Bar(Parcel in) {
    id = in.readInt();
}

public Bar(int id, Map<String,String> map){
    this.hash=map;
    this.id=id;
}

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

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

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

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

I have used Android studios to implement the Parcelable Intel sense help and automatically generate the above code. It does not have the implementation of map

When I send this to my fragment:

 Map<String,String> map = new HashMap<String, String>();
    map.put("foo","bar");
    map.put("foobar","barfoo");
    Bar foo = new Bar(1,map);

    MyFragment fragment = new MyFragment();
    Bundle bundle = new Bundle();
    fragment.setArguments(bundle);
    bundle.putParcelable("foo",foo);
    FragmentTransaction fragmentTransaction =  
    getSupportFragmentManager().beginTransaction();
    fragmentTransaction.add(R.id.container, fragment, "foo");
    fragmentTransaction.commit();

Somehow, the map seems to contain what appears in the fragment. Why? The behavior I will think of is that the ID is transferred and the map is skipped. Just create an activity, a fragment and my bar and send them as a bundle to repeat this operation. I tried to find the answer, but I'm not sure how to formulate the question

Is it an error or function that should work this way?

resolvent:

Parceling is lazy, which means that when you pass it to fragment, your bar instance will not be split. That is, writetoparcel is not called

Parceling is quite expensive (in terms of resources), so it's best to avoid using it if possible. If you don't send the bundle to another process, you don't need to wrap it. It is usually partitioned when IPC is involved. Therefore, you don't need to package the bundle even during configuration changes. However, if your process is terminated while the activity is in the background, the bundle will be surrounded, Because it is stored in another process. The same is true when you send it in intent

Therefore, in your case, when the instance is actually allocated, the map will be lost. It just still exists because it is not a real partition, and the fragment receives exactly the same bar instance

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>