Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing data through navigation between fragments android studio

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

1 Answers

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");
  }
}
like image 183
Dannly Avatar answered Nov 21 '25 10:11

Dannly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!