How To Pass Data From Activity To Fragment Using Bundle
I am completely new to Android and I have to submit this app to end my college degree, but I am having this problem where my fragment crashes my entire app. To explain what I have
Solution 1:
While creating bundle:
Bundlebundle=newBundle();
bundle.putString("userId", userId);
Fragmentfragment=newFragment();
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_placeholder_id, dataFragment, "anyTagName").commit();
The To get the data in your fragment:
if (getArguments != null) {
StringuserId= getArguments().getString("userId");
}
Solution 2:
When you create a new fragment you have an auto-generated function called newInstance
.
So what you need to do is:
publicstaticMyFragmentnewInstance(String param1, String param2) {
MyFragment fragment = newMyFragment();
Bundle args = newBundle();
args.putString("ARG_NAME", param1);
args.putString("OTHER_ARG_NAME", param2);
fragment.setArguments(args);
return fragment;
}
Then, in your activity:
Stringstr1="foo";
Stringstr2="bar";
MyFragmentmyFragment= MyFragment.newInstance(str1, str2);
FragmentTransactiontransaction= getSupportFragmentManager()
.beginTransaction()
.replace(R.id.nameOfActivityLayout, myFragment);
transaction.addToBackStack(null); // Add this line if you want to add the fragment to the back-stack
transaction.commit();
And back to your fragment, in your onCreate
method :
String str1;
@OverridepublicvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
str1 = getArguments().getString("ARG_NAME");
}
}
The variable str1
will now have the value "foo"
and you're free to use it in your fragment. Of course you can put other types in the bundle, like integers, booleans, arrays etc.
Solution 3:
You are using the jetpack navigation component, so its easier than before. You just have to pass the bundle to the navigation controller
Do:
navController.setGraph(R.navigation.graph, YOUR_BUNDLE);
then in your start fragment: Bundle b = getArguement(); String id = b.Get string("I'd");
Post a Comment for "How To Pass Data From Activity To Fragment Using Bundle"