Reputation:
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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?
Upvotes: 4
Views: 10049
Reputation: 138
In your fragment create
(a) Two fields:
listener mCallback;
Activity mActivity;
(b) Interface:
interface mydataBack(){
public void bringBackString(String stringSentBack);
}
(c) Method
@Override
public void onAttach(Activity activity) {
mActivity=activity;
super.onAttach(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
}
Upvotes: 6
Reputation: 191
you have yo use
public static String mydata = "hello "
and then get it in activity by using df.mydata
Upvotes: -2