Search code examples
androidandroid-studioandroid-fragmentsandroid-bundle

getArguments return null when passing data between fragments


I have 2 fragments called MedListFragment and MedDetailFragment. In MedListFragment there is a listview with items of Medicine object. When an item is clicked, MedDetailFragment will open with Medicine object passed from MedListFragment.This is the on item click listener in MedListFragment.

MedListFragment

medlist = (ListView) root.findViewById(R.id.medlist);

medlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Medicine med = (Medicine) adapterView.getItemAtPosition(i);

        FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        Bundle bundle = new Bundle();
        bundle.putParcelable("medicine", med);

        MedDetailFragment medDetailFragment = new MedDetailFragment();
        medDetailFragment.setArguments(bundle);

        fragmentTransaction.replace(R.id.fragment_container, new MedDetailFragment());
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }
});

Then in MedDetailFragment, I get the bundle like this:

public class MedDetailFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_med_detail, container, false);

        Bundle bundle = getArguments();

        Medicine medicine = bundle.getParcelable("medicine");

        return root;
    }
}

But it returns error on line Medicine medicine = bundle.getParcelable("medicine"); saying:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Parcelable android.os.Bundle.getParcelable(java.lang.String)' on a null object reference

Why are the arguments turn null? How exactly to get the bundle? Any help would be appreciated.


Solution

  • Take a look at these lines

    MedDetailFragment medDetailFragment = new MedDetailFragment();
    medDetailFragment.setArguments(bundle);
    
    fragmentTransaction.replace(R.id.fragment_container, new MedDetailFragment());
    

    You are creating two different object of MedDetailFragment. And not passing the object in which you have added the bundle.

    Change this Line

    fragmentTransaction.replace(R.id.fragment_container,medDetailFragment );