Access Activity Variables in Fragment

12,412

Solution 1

A good way for implementing it is to use an interface, as the official documentation suggests.

To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity.

So, basically inside your fragment you define an interface like this:

public interface MyListener {
     public void onAction();
}

and define (still in the fragment) a field of type MyListener

MyListener mCallback;

Then you can set this listener using the onAttach(Activity) method:

mCallback = (MyListener) activity;

Now, each time you want call from your fragment a method in the activity you can use the callback:

mCallback.onAction();

Of course, your Activity need to implement the interface, otherwise you will get an exception while casting your activity to MyListener.

So, just do:

public class MyActivity extends Activity implements MyFragment.MyListener {
    @Override
    public void onAction() {
        // some stuff
    }
}

For more details take a look at the documentation about communication between fragments

Solution 2

If VARIABLE_NAME is a variable in you activity ACTIVITY_NAME and can be accessed from outside Activity ACTIVITY_NAME

Then use this code:

((ACTIVITY_NAME)this.getActivity()).VARIABLE_NAME //this refers to your fragment
Share:
12,412
Jude Fernandes
Author by

Jude Fernandes

I am a partner and one of the co-founders of Octalogic Tech located in Goa. We craft beautifully designed softwares and websites along with mobile apps.

Updated on June 08, 2022

Comments

  • Jude Fernandes
    Jude Fernandes almost 2 years

    If i have an Activity A which extends a base activity BA then i am able to safely access any variable in activity BA from activity A.What i am using now contains an activity A which includes a fragment F. Now from this fragment i want to access all variables of A in the same manner,just like i did above and if not is there a safe way of doing it other than making it available through public methods.

    Or is there a way i can copy over the variables in the base activity to a base fragment so its available in all activities and fragments.

  • Shirish Herwade
    Shirish Herwade almost 7 years
    I tried above, but in this case(i.e. OP's case), its useless... because finally you have to use getter methods in Activity, and so there was no need to implement this interface type hierarchy. Your example is actually useful when you want access/send values across fragments i.e. from one fragment to another
  • Smack Alpha
    Smack Alpha almost 3 years
    Not working on latest appcompat:1.3.1 version