-1

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)

2 Answers2

0

Declare the global variable and then use it. Like this

Mainactivity.java

static public int a;

Fragment1

Mainactivity.a=1

Fragment2

Somevar=Mainactivity.a
MrShakila
  • 874
  • 1
  • 4
  • 19
0

Fragment 1 (Sending data):

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);

remove the onCreate method from Fragment 2, and replace it with the following onCreateView method:

@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_service_detail, container, false);

    if (getArguments() != null) {
        int serviceId = getArguments().getInt("Id");
        // Now you can use the serviceId value as needed
    }

    return view;
}
Saurabh
  • 164
  • 2
  • public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Bundle b = getArguments(); if (b != null) { serviceId = b.getInt("Id"); } Done (i've used OnCreate 'cause I want that methoud would be called once and not every time)... but results are the same... always null :( – Denis De Pauli Apr 25 '23 at 07:24