Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass values between Fragments

People also ask

How do you pass variables between fragments?

To pass data between fragments in the same fragment manager, the listener should be added to the destination fragment with requestKey in order to receive the result produces from another fragment with the same key.

How do you pass data from second fragment to first fragment?

In one fragment activity, call a method and pass a variable to the main activity. From the main activity you can send it to your other fragment activity if you'd like. Show activity on this post. You can also use SharedPreferences to save some string and after return back to the first fragment load it and clear.

How do you pass data between fragments using ViewModel?

Sharing data between fragments is super easy if you use Navigation Architecture Component in your project. In the Navigation component, you can initialize a ViewModel with a navigation graph scope. This means all the fragments in the same navigation graph and their parent Activity share the same ViewModel.


Step 1: To send data from a fragment to an activity

Intent intent = new Intent(getActivity().getBaseContext(),
                           TargetActivity.class);
intent.putExtra("message", message);
getActivity().startActivity(intent);

Step 2: To receive this data in an Activity:

Intent intent = getIntent();
String message = intent.getStringExtra("message");

Step 3: To send data from an activity to another activity, follow the normal approach

Intent intent = new Intent(MainActivity.this,
                           TargetActivity.class);
intent.putExtra("message", message);
startActivity(intent);

Step 4: To receive this data in an activity

  Intent intent = getIntent();
  String message = intent.getStringExtra("message");

Step 5.: From an Activity you can send data to a Fragment with the intent as:

Bundle bundle = new Bundle();
bundle.putString("message", "From Activity");

// Set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

And to receive a fragment in the Fragment onCreateView method:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
    String strtext = getArguments().getString("message");

    return inflater.inflate(R.layout.fragment, container, false);
}

// In Fragment_1.java

Bundle bundle = new Bundle();
bundle.putString("key","abc"); // Put anything what you want

Fragment_2 fragment2 = new Fragment_2();
fragment2.setArguments(bundle);

getFragmentManager()
      .beginTransaction()
      .replace(R.id.content, fragment2)
      .commit();

// In Fragment_2.java

Bundle bundle = this.getArguments();

if(bundle != null){
     // handle your code here.
}

Hope this help you.


As noted at developer site

Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

communication between fragments should be done through the associated Activity.

Let's have the following components:

An activity hosts fragments and allow fragments communication

FragmentA first fragment which will send data

FragmentB second fragment which will receive datas from FragmentA

FragmentA's implementation is:

public class FragmentA extends Fragment 
{
    DataPassListener mCallback;
    
    public interface DataPassListener{
        public void passData(String data);
    }

    @Override
    public void onAttach(Context context) 
    {
        super.onAttach(context);
        // This makes sure that the host activity has implemented the callback interface
        // If not, it throws an exception
        try 
        {
            mCallback = (OnImageClickListener) context;
        }
        catch (ClassCastException e) 
        {
            throw new ClassCastException(context.toString()+ " must implement OnImageClickListener");
        }
    }
    
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) 
    {
        // Suppose that when a button clicked second FragmentB will be inflated
        // some data on FragmentA will pass FragmentB
        // Button passDataButton = (Button).........
        
        passDataButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (view.getId() == R.id.passDataButton) {
                    mCallback.passData("Text to pass FragmentB");
                }
            }
        });
    }
}

MainActivity implementation is:

public class MainActivity extends ActionBarActivity implements DataPassListener{
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        if (findViewById(R.id.container) != null) {
            if (savedInstanceState != null) {
                return;
            }
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new FragmentA()).commit();
        }
    }
    
    @Override
    public void passData(String data) {
        FragmentB fragmentB = new FragmentB ();
        Bundle args = new Bundle();
        args.putString(FragmentB.DATA_RECEIVE, data);
        fragmentB .setArguments(args);
        getFragmentManager().beginTransaction()
            .replace(R.id.container, fragmentB )
            .commit();
    }
}

FragmentB implementation is:

public class FragmentB extends Fragment{
    final static String DATA_RECEIVE = "data_receive";
    TextView showReceivedData;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_B, container, false);
        showReceivedData = (TextView) view.findViewById(R.id.showReceivedData);
    }
    
    @Override
    public void onStart() {
        super.onStart();
        Bundle args = getArguments();
        if (args != null) {
            showReceivedData.setText(args.getString(DATA_RECEIVE));
        }
    }
}

I hope this will help..


From the Developers website:

Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

You can communicate among fragments with the help of its Activity. You can communicate among activity and fragment using this approach.

Please check this link also.