info@androidpaper.co.in

How to Communicate Between Fragments in Android?

In Android Studio, communicating between fragments is a common requirement when building complex applications. Fragments are modular components of an Android app that can be reused and combined to create a dynamic user interface. To facilitate communication between fragments, there are several approaches you can take:

Using a shared ViewModel: Create a shared ViewModel using the Android Architecture Components, such as ViewModel and LiveData. Both fragments can access the ViewModel using the ViewModelProvider and observe changes using LiveData. When one fragment updates a value in the ViewModel, the other fragment can receive the updated value through the observed LiveData. Using an interface: Define an interface in the fragment that wants to send data or communicate with another fragment. Implement the interface in the hosting activity or a parent fragment. Pass the reference of the implemented interface to both fragments. The fragment that wants to send data can call the interface methods to communicate with the other fragment. Here's an example of using an interface for communication between fragments: In the sending fragment:

public class FirstFragment extends Fragment {

    private FragmentFirstBinding binding;
    private CommunicationInterface communicationInterface;

    // Interface for communication
    public interface CommunicationInterface {
        void sendData(String data);
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        // Check if the hosting activity implements the interface
        if (context instanceof CommunicationInterface) {
            communicationInterface = (CommunicationInterface) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement CommunicationInterface");
        }
    }

    // Method to send data to the receiving fragment
    private void sendDataToReceivingFragment() {
        String data = "Hello, Receiving Fragment!";
        communicationInterface.sendData(data);
    }

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

        binding = FragmentFirstBinding.inflate(inflater, container, false);
        return binding.getRoot();

    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        binding.buttonFirst.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendDataToReceivingFragment();
                NavHostFragment.findNavController(FirstFragment.this)
                        .navigate(R.id.action_FirstFragment_to_SecondFragment);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

}

In the receiving fragment:

public class SecondFragment extends Fragment implements FirstFragment.CommunicationInterface {
    private FragmentSecondBinding binding;
    // Implement the interface method
    @Override
    public void sendData(String data) {
        // Process the received data
        Toast.makeText(getActivity(), "Received data: " + data, Toast.LENGTH_SHORT).show();
    }



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

        binding = FragmentSecondBinding.inflate(inflater, container, false);
        return binding.getRoot();

    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        binding.buttonSecond.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NavHostFragment.findNavController(SecondFragment.this)
                        .navigate(R.id.action_SecondFragment_to_FirstFragment);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

}

In the Activity:

public class MainActivity extends AppCompatActivity implements FirstFragment.CommunicationInterface {

    private AppBarConfiguration appBarConfiguration;
    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityTestBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        setSupportActionBar(binding.toolbar);

        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_test);
        appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);

        binding.fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAnchorView(R.id.fab)
                        .setAction("Action", null).show();
            }
        });

            }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_test);
        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp();
    }

    @Override
    public void sendData(String data) {
        Toast.makeText(this, "Received data: " + data, Toast.LENGTH_SHORT).show();
    }
}

Remember to replace "SendingFragment" and "ReceivingFragment" with your actual fragment class names. By implementing the interface in the hosting activity or parent fragment, you can define your own communication contract and exchange data or trigger actions between fragments. Choose the approach that best suits your needs based on the complexity of your communication requirements. Each method has its own benefits and is suitable for different scenarios.