简体   繁体   中英

Send object from Activity to Fragment using Bundle

I have 2 objects (myProfile and employee) in my Activity and i want to send it to my Fragment. I used bundle, example from stackoverflow, but it is giving me errors.

I have follow this stackoverflow example below, but failed. Most examples in stackoverflow is showing on how to pass STRING value ... BUT i want to send an OBJECT .

Send data from activity to fragment in android

https://medium.com/@hamidgh/sending-objects-to-fragment-naive-question-is-it-sent-by-value-ddaaa19fa42d

In Activity

fragment = new MyProfile_FragmentActivity();
Bundle bundle = new Bundle();
bundle.putParcelable("myProfile", (Parcelable) myProfile);
bundle.putParcelable("employee", (Parcelable) employee);
fragment.setArguments(bundle);

In Fragment

public View onCreateView(LayoutInflater inflater, ViewGroup container, 
    Bundle savedInstanceState) {

    MyProfile myProfile = getArguments().getParcelable("myProfile");
    Employee employee = getArguments().getParcelable("employee");

    View rootView = inflater.inflate(R.layout.activity_my_profile, container, false);
    return rootView;
}

Employee.java

public class Employee implements Parcelable {

    //Retrieve from QRCODE
    private String id="";                              
    private String ip_address="";                      
    private Integer activated;

    //My Profile
    private String contact="";                          
    private String email="";                           
    private String name="kirpal";                      

    //Retrieve from device
    private String deviceID="";

    protected Employee(Parcel in) {
        id = in.readString();
        ip_address = in.readString();
        if (in.readByte() == 0) {
            activated = null;
        } else {
            activated = in.readInt();
        }
        contact = in.readString();
        email = in.readString();
        name = in.readString();
        deviceID = in.readString();
    }

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

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

    //SET
    public void set_id(String id){
        this.id = id;
    }

    public void set_ip_address(String ip_address){
        this.ip_address = ip_address;
    }



    //GET

    public String get_id(){
        return this.id;
    }

    public String get_ip_address(){
        return this.ip_address;
    }




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

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(id);
        parcel.writeString(ip_address);
        if (activated == null) {
            parcel.writeByte((byte) 0);
        } else {
            parcel.writeByte((byte) 1);
            parcel.writeInt(activated);
        }
        parcel.writeString(contact);
        parcel.writeString(email);
        parcel.writeString(name);
        parcel.writeString(deviceID);
    }
}

Error Log

java.lang.ClassCastException: nextrackdomain.nextrack.MyProfile cannot be cast to android.os.Parcelable
at nextrackdomain.nextrack.MainActivity.onNavigationItemSelected(MainActivity.java:205)
at android.support.design.widget.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:182)
at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
at android.support.design.internal.BottomNavigationMenuView$1.onClick(BottomNavigationMenuView.java:95)
at android.view.View.performClick(View.java:5181)
at android.view.View$PerformClick.run(View.java:20887)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5938)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1389)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1184)

Both MyProfile and Employee don't implement Parcelable

The hard way: Make your classes implement Parcelable as per the documentation .

The easy way: Add this lib . That will auto generate that for you. Will just need to do

bundle.putParcelable("myProfile", Parcels.wrap(myProfile));
bundle.putParcelable("employee", Parcels.wrap(employee());

MyProfile myProfile = Parcels.unwrap(getArguments().getParcelable("myProfile"));
Employee employee = Parcels.unwrap(getArguments().getParcelable("employee"));

and add the @Parcel annotation on your classes:

@Parcel
public class MyProfile{//rest of the normal code}

@Parcel
public class Employee{//rest of the normal code}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM