1

I would like know how can I get and set a value of my activity from my fragment?? is that possible?

below is my activity and the attribute 'myStation' is the value I want get and set from my fragment.

public class MyActivity extends Activity
    implements NavigationDrawerFragment.NavigationDrawerCallbacks {

public static Station myStation;

In my fragment I can execute 'getActivity()' but I really don't know if I can do that. if I'm wrong, what is the correct process?¿

Thanks.

gon250
  • 3,405
  • 6
  • 44
  • 75
  • 1
    Firstly, never define a `public static` variable in an `Activity`. Secondly, all communication between a `Fragment` and the `Activity` it is attached through should be done through methods in the callback interface and the `Activity` should be responsible for getting / setting the value. – Squonk Oct 20 '14 at 19:15
  • thanks, can you provide me an example?¿ please will help me a lots. – gon250 Oct 20 '14 at 19:18
  • @ShirishHerwade I think is a different question – gon250 May 10 '17 at 07:19
  • hhmmm... but i think still it's a dupliacte though... there are a lot question like these from 2012 onward e.g. http://stackoverflow.com/questions/12659747/call-an-activity-method-from-a-fragment – Shirish Herwade May 10 '17 at 07:22

1 Answers1

2

If the fragment is only used in that activity, then you can simply cast the activity. Otherwise you'll have to verify that it is the correct activity perhaps using instance of.

Let's look at the simpler case:

public class MyActivity extends Activity {

    private boolean myFlag;

    public boolean getMyFlag() {
        return myFlag;
    }

    public void setMyFlag(boolean myFlag) {
        this.myFlag = myFlag;
}

And here would be the fragment to adjust the flag.

public class MyUniqueFragment extends Fragment {

    public void updateActivityFlag(boolean myFlag) {
        MyActivity myActivity = (MyActivity) getActivity();
        myActivity.setMyFlag(myFlag);
    }
}
Razz
  • 220
  • 1
  • 6