Kuldeep Yadav Kuldeep Yadav - 2 months ago 53
Android Question

Android - Bundle savedInstanceState is null in Fragment onCreate() and onCreateView()

I am trying to pass arguments to a

Fragment
.

On clicking
View
of a
Fragment
, I replace my
Fragment
with another and pass data to be used into next
Fragment
.

My click action :

public void onClick(View view) {
Bundle args = new Bundle();
args.putSerializable("order", orders.get(position));
OrderDetailFragment orderDetailFragment = new OrderDetailFragment();
orderDetailFragment.setArguments(args);
FragmentManager fragmentManager = ((AppCompatActivity) context).getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.order_activity_content_frame, orderDetailFragment)
.addToBackStack("orderDetails")
.commit();
}


But in my destination
Fragment
,
savedInstanceState
is coming to be
null
.

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);

order = (Order) savedInstanceState.getSerializable("order");

View rootView = inflater.inflate(R.layout.fragment_order_details, container, false);
TextView date = (TextView) rootView.findViewById(R.id.order_detail_date);
date.setText((CharSequence) order.getCreatedOn());
return rootView;
}


I am not able to figure out what exactly am I missing?

Answer

savedInstanceState contains the data saved in onSaveInstanceState(), which is called before your Activity/Fragment is getting killed by the OS (to reclaim memory for example, or because of an orientation change).

Call getArguments() to get the Bundle you saved with setArguments():

order = (Order) getArguments().getSerializable("order");

Also, the recommended practice to instantiate a Fragment with arguments is via a static newInstance() method, something like this:

public static OrderDetailFragment newInstance(Order order) {
    Bundle args = new Bundle();
    args.putSerializable(KEY_ORDER, order);
    OrderDetailFragment fragment = new OrderDetailFragment();
    fragment.setArguments(args);
    return fragment;
}

And then you instantiate your Fragment like this:

OrderDetailFragment orderDetailFragment = OrderDetailFragment
    .newInstance(orders.get(position));