How to access Activity Variables from a fragment Android

how to go from activity to fragment in android
pass data from activity to fragment
implement interface in fragment android
fragment to fragment communication without activity
android fragment example
how to use interface to communicate between two activities
activity to fragment communication
android fragment get value from parent activity

In the Activity I have :

public class tabsmain extends Activity{
    public static Context appContext;

    public boolean lf_ch=false;

    public void onCreate(Bundle savedInstanceState){

I would like to access and possibly change lf_ch from a fragment inside tabsmain;

public class tabquests extends Fragment{ 
    public CheckBox lc;
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)//onCreateView
    { 
lc.setChecked(//set it to lf_ch);

However, I can't seem to access the value of lf_ch.

Try this:

public View onCreateView(...){
  tabsmain xxx = (tabsmain)getActivity();
  lc.setChecked(xxx.lf_ch);
}

Access Activity Variables in Fragment, 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  This example demonstrates how do I pass a variable from activity to Fragment in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. Step 3 − Add the following code to src/MainActivity.java. Step 5 - Add the following code to androidManifest.xml.

I know this is an old question, however here is an easy answer that work without jumping through any hoops. In you Fragment define a variable that is the Activity that the fragment will be in then in the onCreateView connect the variable to the activity and then you have a reference that can get to any public variable in the main activity. I had forgotten it when I ended up here. It's a little hard to do the other way as you need to find the exact fragment that is showing. However with this you shouldn't need to do it the other way because you can easily pass things back and forth. I hope this help anyone that comes across it.

public Quiz_Avtivity mainQuiz;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_quiz, container, false);

mainQuiz = (Quiz_Avtivity) getActivity();
//Below is where you get a variable from the main activity
mainQuiz.AnyPublicVariable = whatEver;
//also
whatEver = mainQuiz.AnyPublicVariable

How to pass a variable from Activity to Fragment in Android?, This example demonstrates how do I pass a variable from activity to Fragment in android.Step 1 − Create a new project in Android Studio, go to  In you Fragment define a variable that is the Activity that the fragment will be in then in the onCreateView connect the variable to the activity and then you have a reference that can get to any public variable in the main activity. I had forgotten it when I ended up here.

if you are using Java, you can use

((YourActivityName)getActivity()).variableName

to access, and if you are using Kotlin, you can use

(activity as YourActivityName).variableName

If the variable is defined as null in kotlin, you have to try each of these method as well:-

(activity as? YourActivityName).variableName

(activity as? YourActivityName)!!.variableName

or have to use let block, if possible.

Choose the correct one for you!

Hope, It will help.

How to transfer data from activity to fragment , and from fragment to , How to transfer data from activity to fragment , and from fragment to fragment using a View Model src : https://developer.android.com/topic/libraries/​architecture/viewmodel Initialize a variable (line 5); Reference view model (line 13). To get data or store data simply use the getter and setter methods , this  Android passing variables from activity to fragment When you use Fragment to create dynamic and multi-pane UI applications in Android, you might want to pass variables from an activity to a fragment so that they can be used in that fragment.

take Activity value in fragment.

((MainActivity) getActivity()).mGoogleApiClient;

Communicate with other fragments, Both fragments can access the ViewModel through their containing Activity. Here's an example of Fragment to Activity communication:. Open the activity_main.xml, delete the TextView and change the root ViewGroup contain to RelativeLayout. Then, switch to the design view of the Android Studio if you are not using it already. In the custom section, click on the <fragment> menu to open is pop-up window. Select the FirstFragment and click Ok.

Another way to get data from activity is to access activity's intent via:

getActivity.getIntent().getExtras();

and etc.

It can be useful if you starts activity with fragment in xml, and would like to control somehow fragment's onCreate() behavior.

PS: of cause you should firstly put something to intent

Android passing variables from activity to fragment, In this Android tip, I am going to show you how to accomplish this task. Now to have a workable application to demonstrate the task, create a new  I need to pass the job object to these fragments so that it can display respective information. I have created container activity and tab fragments. I would need an example on how to pass the object across them. I cannot use intent.putExtra. Can I access parent container's object from fragment? Any help shall be appreciated. Thanks.

Android: how can fragment take a global variable of Activity, How to access Activity Variables from a fragment Android, How to define an Android Global variable in Android studio? Then we can access your global data or  You don't want to access Activity's variables directly from another (outer) class. This is a bad practice, as Activities are, after all, part of the UI, and not the backend of the application. Also, note that in your example, the name property is static and doesn;t belong to a specific instance.

Android Fragments Tutorial: An Introduction with Kotlin , In this Android Fragments with Kotlin tutorial you will learn the It also provides an interface for you to access, add and remove those fragments. a tool where you could bind a variable from your fragments and activities to  Here, the highValue, updatePeriodValue and selectedSensor are the variables being used in the Lux Meter fragment in PSLab Android app. But they can be replaced by the necessary variables as per the app. So, in this way, we can pass data between the fragments of the same Activity in an Android application.

1.2: Fragment lifecycle and communications · GitBook, As with an Activity , you can save the variable assignments in a Fragment . Likewise, a Fragment can get a reference to its hosting Activity to access resources, and you select the Include fragment factory methods option, Android Studio  To emit or pass data from our input fragment create ViewModel in activity scope. To do this we have to pass the activity reference as argument of the ViewModelProvides.of () method. Noe just pass

Comments
  • my 2 cents: static Context field is bad, mkay ... and name convetion ... try to not use only small letters in class names 'tabsmain' => 'TabsMain' ... it ok to name var (like: TabsMain tabsmain = null;) but when you wana use this class like in David M answer it's hard to know if tabsmain is class name or var ... look t Android SDK classes, java classes they always use first upper
  • I hope you've been to one or two variable naming conventions since you posted this :)
  • I agree with Selvin. Java world is very particular about naming convention. Please see javatpoint.com/java-naming-conventions. Thanks for the answer.
  • this will only help in reading the variables for the object xxx. However, if I want to read the same variables in the other fragment it wont work.
  • i could change it as well. improvement : you can you directly as tabsmain.lf_ch you can change as tabsmain.lf_ch=new_value
  • No problem. Glad to help. If it wasn't for the help I've gotten here I never would have finished any projects. Just thought I would give back since I could.
  • ...so true! :D ...Thumbs up to stackoverflow team and every one who take the time to give back to the community! :D
  • I've been using the same method and it seems to work fine. But as I see a lot of recommendations to use an interface between activity & fragments, I've been wondering if this is really "okay" to do, knowing that my fragments are really meant to only be used with that one activity.
  • I've had an app in the app store that uses this method. The app has been there for a year now and I have seen no failures that have been caused by doing it this way. As with yours my fragments are used with one activity. I guess if you wanted to use a fragment with more than one activity or visa versa using an interface would be the way to go, in fact to do it this way you have to know exactly what activity the fragment is in. If you tried to use this method putting a fragment into with more than one activity it wouldn't work.
  • This is the best and safest approach and should have been the accepted answer. The other answers doesn't follow android guidelines which states "Fragments are meant to be re-usable and having to cast getActivity to a specific activity class is a bad practice because it limits it's usage to that activity and will throw NPE of any other".
  • Excellent response! One question: Doesn't need tabsmain Activity to add "Implements MyResultReceiver" to implement it? because it actually define the getResult() method, but I can't see why says @Override if the interface is not implemented... I just ask because I'm learning Java, and I'm not sure if it is correct what I'm saying.
  • Yes, the activity should implement it. Good catch @FerB. Updated my code