Reputation: 946
Hi I'm trying to pass a string variable from an activity into a fragment but it's always null.
Firstly I set the variable value, then create the bundle in the Activity:
String results = setResultCaption(bothEarsBad, leftEarBad, rightEarBad).toString();
Then
Bundle bundle = new Bundle();
bundle.putString("resultsString", results);
RightEarResults rightEarResults = new RightEarResults();
rightEarResults.setArguments(bundle);
I then call the bundle
from the fragment onCreateView
method as follows:
String bundle = getArguments().getString("resultsString");
And then set the variable in the TextView
txt = (TextView) rootView.findViewById(R.id.results_text);
txt.setText(bundle);
Can anyone help me understand why it's always null.
Upvotes: 0
Views: 1026
Reputation: 5425
You can just do:
From your activity;
Intent passIntent = new Intent(MainActivity.this, Yourclass.class);
passIntent.addExtra("resultsString",results);
startActivity(passIntent);
In your fragment;
Intent intentBundle = getActivity().getIntent();
String someresult= intentBundle.getStringExtra("resultsString");
Log.i("Result : ", someresult);
And then,
txt = (TextView) rootView.findViewById(R.id.results_text);
txt.setText(someresult);
Upvotes: 0
Reputation: 6905
If you want to pass variables on fragment initialisation, you can :
Use a bundle as parameter of Fragment.setArgument()
method
Use a static method with your variables as parameters. Check @Philipp Jahoda's answer.
If you want to pass variables to fragment after initialisation, you can refer to this post from the official doc
Upvotes: 0
Reputation: 51411
Provide a newInstance()
method for your Fragment
and hand over the parameter there:
public static YourFragment newInstance(String valueToPass) {
YourFragment f = new YourFragment();
Bundle b = new Bundle();
b.putString("key", valueToPass);
f.setArguments(b);
return f;
}
In your Actitity
:
getSupportFragmentManager().beginTransaction().replace(R.id.container, YourFragment.newInstance(stringtoPass), "yourFragTag").commit();
Inside your Fragment
, you can then retrieve the value by using the getArguments()
method:
String yourvalue = getArguments().getString("key");
EDIT : Also, please check if your setResultCaption(...)
method actually returns something, and not NULL.
Upvotes: 1