Reputation: 805
Is there a way to check which activity loads a fragment from within the fragment? I have a user profile fragment which is loaded from 2 different activities but only one passes a value in, so when getting values from the bundle when the fragment loads from the activity that doesn't pass a value throws a nullpointerexception. Or is there a better way to pass the value into the fragment so the fragment can get the value only when loaded from this specific activity?
Upvotes: 0
Views: 3786
Reputation: 11921
You can define two static methods (also known as Static Factory Methods) which returns instances of your Fragment
with the parameters you want to pass with bundle like the following code:
private static final String BUNDLE_VALUE_KEY = "value";
@NonNull
public static YourFragment newInstance() {
return new YourFragment();
}
@NonNull
public static YourFragment newInstance(@NonNull String yourValue) {
final YourFragment instance = new YourFragment();
final Bundle args = new Bundle();
args.putString(BUNDLE_VALUE_KEY,yourValue);
instance.setArguments(args);
return instance;
}
In your Activity
which you want to pass the value you can use:
final YourFragment fragment = YourFragment.newInstance(value);
getSupportFragmentManager().beginTransaction()
.replace(R.id.framelayout, fragment)
.commit();
In other Activity
you can use:
final YourFragment fragment = YourFragment.newInstance();
getSupportFragmentManager().beginTransaction()
.replace(R.id.framelayout, fragment)
.commit();
And in onCreate
method of your Fragment
you can check arguments and init your value like the following code:
final Bundle args = getArguments();
if(args != null){
yourValue = args.getString(BUNDLE_VALUE_KEY,null);
}
So if your Fragment
is attached to the Activity
which passes data you'll have it. If the Fragment
is attached to other Activity
you'll have the initial value (in the example it's null
)
Or you can check the instance of Activity
which Fragment
gets attached. (Not best practice)
if(getActivity() instanceof YourActivityWhichPassesData){
yourValue = getArguments().getString(BUNDLE_VALUE_KEY,null);
}
Upvotes: 1
Reputation: 3819
You can simply do this check in your fragment:
if(getActivity() instanceof SomeActivity){
//do something
}
You can also cast the getActivity()
call if you are sure which Activity it is (and then call methods from that Activity).
Upvotes: 6