deepak deepak - 1 year ago 158
Android Question

How to access fragment variable into main activity class

I have 1 main activity class and 1 fragment class:

I want to access variable of fragment class into my main activity class:

Myfragment class:

public class DemoFragment extends Fragment {

Public String mydata="hello";
.. //other code

Mainactivity class:

public class MainActivity extends ActionBarActivity {

..//other code
DemoFragment df;

protected void onCreate(Bundle savedInstanceState) {
mContext = this;

df = new DemoFragment();

String newdata = df.mydata; //access from fragment but it shows null



So how can i access fragment class variable values into main activity?

Answer Source

In your fragment create

(a) Two fields:

listener mCallback;
Activity mActivity;

(b) Interface:

interface mydataBack(){
   public void bringBackString(String stringSentBack);

(c) Method

        public void onAttach(Activity activity) {
        mCallback = (listener) mActivity;

Then in the Fragment call the method bringBackString(String) when you wish to send back the string.

In your mainactivity:

(a) add in the "implements.. ...listener" in the class declaration

public class MainActivity extends ActionBarActivity implements DemoFragment.listener {  etc   and

(b) implement the interface method:

public void bringBackString(String stringBroughtBack){
....  do something with the string
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download