Access the variables of the activity from its fragment

1

ACTIVITY

I have the activity with the following global variables:

public String variable="";
public static final String KEYVARIABLE= "KEY";

In onCreate I change the value of "variable":

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Intent intent=getIntent();
    variable=intent.getStringExtra(KEYVARIABLE);
}

In onSaveInstanceState add to bundle the data that I collect in onCreate

@Override
public void onSaveInstanceState(Bundle bd) {

    bd.putString(KEYVARIABLE, variable);

}

FRAGMENTO

In the fragment I have as global:

public String variable="";
public static final String KEYVARIABLE= "KEY";

In onCreate :

 variable=savedInstanceState.getString(KEYVARIABLE);

This does not work for me, since it tells me that "variable" is empty. That could be happening? How could you access the global variables of the activity from your fragment?

    
asked by adamista 01.04.2016 в 11:15
source

1 answer

2

If you need to go to Fragment variables in the onCreate method, I recommend that you programmatically . What you have to do then is to pass the variables to him when creating it, to keep them within a Bundle pass it as an argument to Fragment and to recover them when you need them.

You would have something like this:

Activity

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Intent intent=getIntent();
        variable=intent.getStringExtra(KEYVARIABLE);
        TuFragment fragment = TuFragment.newInstance(variable);
        getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, fragment, TAG_FRAGMENT).commit();
    }

Fragment

    public static TuFragment newInstance(String variable) {
        TuFragment fragment = new TuFragment();
        Bundle args = new Bundle();
        args.putString(KEYVARIABLE, variable);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Bundle arg = getArguments();
        if (arg != null)
            variable = arg.getString(KEYVARIABLE);
    }

The method onSaveInstanceState and the argument savedInstanceState of onCreate are not for the use that you want to give, is to save and retrieve the variables you need when the Activity or the Fragment have to be rebuilt .

Greetings.

    
answered by 01.04.2016 / 12:00
source