I have activity and two fragments which opened in this activity (for example FragmentFirst, FragmentSecond). In my activity I register BroadcastReceiver. And when i receive any event (inside onReceive
) I need to display the received text in the TextView of second fragment.
I could register the BroadcastReceiver in the second fragment, however, the event may come at the moment when my second fragment opens and then I do not have time to register the BroadcastReceiver and I lose the event.
So my code inside the onReceive
of activity looks like this:
@Override
public void onReceive(Context context, Intent intent) {
String receivedMessage = intent.getStringExtra(MY_MESSAGE);
Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.container);
if (currentFragment instanceof FragmentSecond) {
((FragmentSecond) currentFragment).initMessage(receivedMessage);
}
}
And now I have a question, can there be such a situation that the current fragment is FragmentSecond
, but the view of this fragment has not yet been created. In this case, I can get a NPE when calling a initMessage
of my FragmentSecond
that sets the receivedMessage
for the TextView
.
If this is really possible, then I will have to add some kind of checks inside the initMessage
:
public void initMessage(String receivedMessage) {
if (isViewCreated) { // flag to detect when view was created
tvMessage.setText(receivedMessage);
savedMessage = "";
} else {
savedMessage = receivedMessage; // save message to display it when view will be created
}
}
In practice, I was not able to reproduce such a situation, but it seems to me that this is possible. Please tell me if this is possible?
P.S. I get the feeling that the onReceive
controls the life cycle and is called exactly when the fragment view is created. Because I tried to send a broadcast until the moment when the FragmentSecond
view was created, but until the onViewCreated
of my FragmentSecond
was called, onReceive
was not called. However, I may be wrong