简体   繁体   中英

Pass an Parcelable Object from an Fragment to an activity

I have a fragment MyFragment

public class MyFragment extends Fragment {
    //Some code here like to constructor

    //Trying to pass an object to another Activity
    Intent i = new Intent(getActivity(), NextActivity.class);
    startActivity(i);
    i.putExtra("test",  parcableObject);
    getActivity().finish();
}

And I have an activity NextActivty

public class NextActivity extends AppCompatActivity {
    //Some code here like to constructor
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.next_activity);

        Intent intent = getIntent();
        mBoard =  intent.getParcelableExtra("test");
        Log.d(TAG, "onCreate: " + mBoard);
}

Here is my Board class

public class Board implements Parcelable {
    //Implements all the Parcelable methods.
    protected Board(Parcel in) { 
        //Auto-generated code here
    }
    public static final Creator<Board> CREATOR = new Creator<Board>() {
        //Auto-generated code here
    }
    @Override
    public int describeContents() {
        //Auto-generated code here
    }
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        //Auto-generated code here
    }
}

My mBoard is always null .

Is there something I am not doing right here ?

You put your extra in wrong order. Put it before you start your activity.

public class MyFragment extends Fragment {
    //Some code here like to constructor

    //Trying to pass an object to another Activity
    Intent i = new Intent(getActivity(), NextActivity.class);
    i.putExtra("test",  parcableObject);
    startActivity(i);
    getActivity().finish();
}

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