I want to pass a value from an activity to fragment via EventBus. I can pass the value and read with @Subscribemethod. But I can't pass the value to a variable at the beginning of onCreateView - setupGridView(mUser). I want to add the value setupGridView as a parameter. Is it possible to get EventBus data at the very beginning of onCreateView()?
private User mUser;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile_pages, container, false);
setupGridView(mUser);// mUser is null here
}
@Subscribe
public void mSetUser(User user){
mUser = user;
Log.d(TAG, "mUser: " + user.toString());//I can see data here
}
@Override
public void onAttach(Context context) {
EventBus.getDefault().register(this);
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
EventBus.getDefault().unregister(this);
}
No, you can't pass the value to
onCreateView()because when you're firing an Event to be received inonCreateView()it would be too early or too late.Here's the explanation:
Fragment lifecycle is starting when the fragment is add to the activity. The fragment is usually added with the following code:
Let's make the above code to a method called addExampleFragment(). So, it will be looks like this:
Now, because we want the
onCreateView()receive the Event, we think that we can send it before adding the Fragment with this:But it won't work because the Fragment not yet created so it doesn't register itself as a subscriber. It's too early to send the Event.
If we want to send the Event after creating the fragment with:
It won't work too because
onCreateView()is already called before the Event is fired. So, it's too late to send the Event.So, you can't use Event for your
onCreateView()problem. You can use Bundle instead.