6

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.

Jude Fernandes
  • 7,437
  • 11
  • 53
  • 90

2 Answers2

6

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

GVillani82
  • 17,196
  • 30
  • 105
  • 172
  • 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 – Shirish Herwade May 10 '17 at 06:58
4

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
Atef Hares
  • 4,715
  • 3
  • 29
  • 61