37

I have an activity with a global variable int x, how can a fragment get the current value of variable x of its activity ?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
esoni
  • 1,362
  • 4
  • 24
  • 37

4 Answers4

94

Either set the var as public static, or use

((MyActivity)getActivity()).getX()
hsz
  • 148,279
  • 62
  • 259
  • 315
Steelight
  • 3,347
  • 1
  • 20
  • 17
18

Using a public static variable isn't the best way to communicate between an activity and a fragment. Check out this answer for other ways:

The Android documentation recommends using an interface when the Fragment wants communicate with the Activity. And when the Activity wants to communicate with the Fragment, the Activity should get a reference to the Fragment (with findFragmentById) and then call the Fragment's public method.

The reason for this is so that fragments are decoupled from the activity they are in. They can be reused in any activity. If you directly access a parent Activity or one of its global variables from within a fragment, you are no longer able to use that fragment in a different Activity.

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
  • but why can't you use the fragment in different activity if we do this. – ams92 Nov 18 '18 at 01:03
  • @ams92, Because the fragment would still have a dependency on the old activity. You would have to change the fragment code every time that you wanted to use it in a new activity. – Suragch Jan 11 '19 at 16:55
12

Kotlin version:

(activity as MyActivity).x
Manohar
  • 22,116
  • 9
  • 108
  • 144
4
***In your Activity
==================
Bundle args = new Bundle();
args.putInt("something", Whatever you want to pass);
fragA.setArguments(args);

In your Fragment
==================
 Bundle args = getArguments();
//whatever you want to get ,get it here.
//for example integer given     
    int index = args.getInt("index", 0);
Kartheek
  • 41
  • 4