I'm trying to pass arguments from my Activity to a Fragment and I'm using this code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
String message = getIntent().getStringExtra(Intent.EXTRA_TEXT);
DetailActivityFragment fragment = new DetailActivityFragment();
Bundle bundle = new Bundle();
bundle.putString(INTENT_EXTRA, message);
fragment.setArguments(bundle);
}
I'm getting the value of the message variable through an Intent Extra and that works fine, so far.
Then I'm passing it as an argument to my fragment but then, when I call getArguments()
from that specific Fragment it returns a null Bundle.
Does anybody have a solution to this?
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null && bundle.containsKey(DetailActivity.INTENT_EXTRA)) {
forecast = bundle.getString(DetailActivity.INTENT_EXTRA);
} else if (bundle == null) {
Toast.makeText(getActivity(), "Error", Toast.LENGTH_LONG).show();
}
}
The upper method displays a Toast message "Error" when I run the app...
The best way to use arguments with your fragment is to use the newInstance function of the fragment.Create a static method that gets your params and pass them in the fragment through the new instance function as below:
public static myFragment newInstance(String param1, String param2) {
myFragment fragment = new myFragment ();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
And then on create set your global arguments:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
on your main activity you will create the fragment like
myFragment __myFragment = myFragment.newInstance("test","test");
That should work
This is a correct approach
Send (in the Activity):
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
final DetailActivityFragment frg = new DetailActivityFragment ();
ft.replace(R.id.container, frg);
final Bundle bdl = new Bundle();
bdl.putString("yourKey", "Some Value");
frg.setArguments(bdl);
ft.commit();
Receive (in the Fragment):
final Bundle bdl = getArguments();
String str = "";
try
{
str = bdl.getString("yourKey");
}
catch(final Exception e)
{
// Do nothing
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With