gkmohit gkmohit - 1 month ago 8
Android Question

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 ?

Answer

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();
}
Comments