Home > Mobile >  passing data through navigation between fragments android studio
passing data through navigation between fragments android studio

Time:11-28

I'm new to android studio and dont fully understand the working of it yet but I've been attempting to send data from one fragment to another in android studio. I've not been able to find a clear answer to this issue. What I'm trying to do is make a basic parking app where a qr code is scanned and the data that is in the qr code (parking name and price per hour) will be send to the next fragment since the qr code scanner fragment will open an addParkingSession fragment where I'll need the parking data. I've been trying to use "Navigation" to do this but i'm unable to find a way to send data via this methode. Is there a different mehode that better suits this (it has to go from fragment to fragment though) I've been trying to use intent but navigation doesn't seem to have an option to send an intent along with it.

Here is some of my code as an example. Thank you for your help and understanding

codeScanner.setDecodeCallback(new DecodeCallback() {
        @Override
        public void onDecoded(@NonNull Result result) {
            getActivity().runOnUiThread(new Runnable(){
                @Override
                public void run(){
                    if(result.getText() != null) {
                        String[] parkingdata = resultData.toString().split(",");
                        Intent intent = new Intent(getActivity().getBaseContext(), AddSession.class);
                        intent.putExtra("parkingName", parkingdata[0]);
                        intent.putExtra("parkingPrice", parkingdata[1]);
                        Navigation.findNavController(view).navigate(R.id.action_qrSession_to_addSession);
                    }
                }
            });
        }
    });

CodePudding user response:

You can pass a bundle object as the second argument in .navigate() and access it in your fragment with getArguments().

final Bundle bundle = new Bundle();
bundle.putString("test", "Hello World!");
Navigation.findNavController(view).navigate(R.id.action_qrSession_to_addSession, bundle);
public class MyFragment extends Fragment {
  
  @Override
  public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    // the string you passed in .navigate()
    final String text = getArguments().getString("test");
  }
}
  • Related