How to correctly save instance state of Fragments in back stack?

To correctly save the instance state of Fragment you should do the following: 1. In the fragment, save instance state by overriding onSaveInstanceState() and restore in onActivityCreated(): class MyFragment extends Fragment { @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); … if (savedInstanceState != null) { //Restore the fragment’s state here } } … @Override public … Read more

Retrieve a Fragment from a ViewPager

The main answer relies on a name being generated by the framework. If that ever changes, then it will no longer work. What about this solution, overriding instantiateItem() and destroyItem() of your Fragment(State)PagerAdapter: public class MyPagerAdapter extends FragmentStatePagerAdapter { SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>(); public MyPagerAdapter(FragmentManager fm) { super(fm); } @Override public int getCount() { … Read more

How to pass values between Fragments

Step 1: To send data from a fragment to an activity Intent intent = new Intent(getActivity().getBaseContext(), TargetActivity.class); intent.putExtra(“message”, message); getActivity().startActivity(intent); Step 2: To receive this data in an Activity: Intent intent = getIntent(); String message = intent.getStringExtra(“message”); Step 3: To send data from an activity to another activity, follow the normal approach Intent intent = … Read more

NullPointerException accessing views in onCreate()

The tutorial is probably outdated, attempting to create an activity-based UI instead of the fragment-based UI preferred by wizard-generated code. The view is in the fragment layout (fragment_main.xml) and not in the activity layout (activity_main.xml). onCreate() is too early in the lifecycle to find it in the activity view hierarchy, and a null is returned. … Read more

Send data from activity to fragment in Android

From Activity you send data with intent as: Bundle bundle = new Bundle(); bundle.putString(“edttext”, “From Activity”); // set Fragmentclass Arguments Fragmentclass fragobj = new Fragmentclass(); fragobj.setArguments(bundle); and in Fragment onCreateView method: @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { String strtext = getArguments().getString(“edttext”); return inflater.inflate(R.layout.fragment, container, false); }