Search code examples
androidandroid-fragmentsbundleandroid-navigation

Passing data between fragments (tried all solutions


I've read (or tryied) all about here but I'm unable to pass a simple integer value between two fragments.

My code is simple

Fragment 1

Bundle n = new Bundle();
n.putInt("Id", 1); // test value
NavController navController = Navigation.findNavController(getActivity(), R.id.nav_host_fragment_content_main);
navController.navigate(R.id.serviceDetailFragment, n);

Fragment 2

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b = getArguments();
if (b != null) {
        `enter code here`serviceId = b.getInt("Id");
    }

}

but b is already NULL (in fragment 1 it is correctly intantiated and value set to a in int i.e. 1 or 2)


Solution

  • Declare the global variable and then use it. Like this

    Mainactivity.java

    static public int a;
    

    Fragment1

    Mainactivity.a=1
    

    Fragment2

    Somevar=Mainactivity.a