title: Data Sharing between Fragments and Activity in Android
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>This is my Code:</p>
  
  <p>Activity:</p>
  
  <pre><code>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);
  
  
      }
  </code></pre>
  
  <p>Fragment 1:(Where I want to read the boolean lf set in Acitivity above:</p>
  
  <pre><code>@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
  </code></pre>
  
  <p>Fragment 2: Where I want to set lf in Activity</p>
  
  <pre><code>.....
  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
                    ;
                }
            });
  </code></pre>
  
  <p>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.</p>
  
  <p>I tried to create a function setlf(boolean jk) but also I am not able to see it...</p>
  
  <p>Any help is welcome :)</p>