Data Sharing between Fragments and Activity in Android
Asked Answered
E

3

34

Ive asked a similar question before and didn't get an answer and seems many other ppl are searching for an answer. So I am posting this question to hopefully get a clear answer that everyone can benefit from.

I have an activity with 2 fragments in it. I want fragment2 to set a boolean variable in Activity when a checkbox is checked so that fragment1 can know if the checkbox was checked.

This is my Code:

Activity:

public class modestab extends Activity{
    public static Context appContext;

    public boolean lf=false;

    public void onCreate(Bundle savedInstanceState){
        appContext=this;
super.onCreate(savedInstanceState);
ActionBar tabbar= getActionBar();
        tabbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        ActionBar.Tab ModesTab =tabbar.newTab().setText("Modes");
        ActionBar.Tab CatTab =tabbar.newTab().setText("Categories");

        Fragment ModesFragment =new modes();
        Fragment CatFragment =new cats();

        ModesTab.setTabListener(new MyTabsListener(ModesFragment));
        CattTab.setTabListener(new MyTabsListener(CatFragment));

        tabbar.addTab(ModesTab);
        tabbar.addTab(CatTab);


    }

Fragment 1:(Where I want to read the boolean lf set in Acitivity above:

@TargetApi(11)
public class tabmodes extends Fragment{
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
View V=inflater.inflate(R.layout.tab_modes, container, false);
button1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if(lf==false) //lf here is the lf in Activity which I want to get

Fragment 2: Where I want to set lf in Activity

.....
lifecheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
              @Override
                public void onCheckedChanged(CompoundButton buttonView,
                        boolean isChecked) {
                  if(lifecheck.isChecked())
                      getActivity().lf=true;//Where I want to set the lf flag in Activity
                  ;
              }
          });

The code doesn't compile and I am not knowing how to set lf in the Activity nor how to read it. Someone suggested I do getActivity() but I am not able to see the variable.

I tried to create a function setlf(boolean jk) but also I am not able to see it...

Any help is welcome :)

Eddi answered 18/11, 2012 at 23:9 Comment(0)
R
121

Many ways :

1) Activity -> Fragment

2) Activity -> Fragment

3) Fragment -> Activity

  • In your Fragment : create un interface with getter and setter methods (callback methods)
  • In your Activity : implement the interface

4) Fragment -> Activity

  • In your Activity : Create public getter and setter or other methods
  • In your Fragment : called public activity getter, setter or other methods using :

    getActivity().getSomething(), getActivity().setSomething(args) or getActivity().someMethod(args)

Refractory answered 11/12, 2013 at 14:32 Comment(3)
You just solved a big problem for me and saved me a whole bunch of work. Thanks!Zoraidazorana
why is it bad to use a static variable . and cant we use a static object instead of static methods and variablesDoggery
Nicely written answer with multiple options really helps. I'm wondering about the trade-offs of each (are there benefits or negatives to each? - or are they all basically equal?) and are these still the 4 main ways in the present (2019) since this answer is 6 years old? Just curious.Consultative
J
2

You can pass data between fragments in two ways,

First, you can do it by using setArguments(...) and getArguments(....)

Second,you can do it using Call back

Juvenility answered 18/11, 2012 at 23:43 Comment(4)
Is this the only way to share data by passing arguments between the fragments? can't I set and get the variables in the activity directly?Eddi
Otherwise you can use sharedpreferences for data sharingJuvenility
I'm pretty new to this, do you have any example on the setArguments and getArgumentsDischarge
For a question that specifically asks for clear answers, yours doesn't help much.Cymatium
G
1

Also you can use EventBus. It's really simple. https://github.com/greenrobot/EventBus

Definitely don't use static methods like my old answer :)

Guenevere answered 18/1, 2016 at 11:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.