Hello! :) There is no ideal solution for this type of problem, at most you can identify names, for example, you can find the name of the activity that called another activity through the getCallingActivity
method.
A solution not recommended would be to use a static method in activity and pass the fragment to a static variable.
But most likely you are wanting to do something that there is a better way to do, if you want to pass information to the fragment that called the activity and identify the moment that activity ends, you should call this activity with the startActivityForResult
and in activity before closing it you should pass the information by intent
with method setResult
Example:
No fragment:
Intent i = new Intent(this, MinhaActivity.class);
getActivity().startActivityForResult(i, 1);
In the activity that was called (MinhaActivity):
Intent retornoIntent = new Intent();
retornoIntent.putExtra("resultadoid",resultado);
setResult(Activity.RESULT_OK,retornoIntent);
finish();
And in the fragment that called MinhaActivity:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String resultado = data.getStringExtra("resultadoid");
//Momento exato quando a activity chamada por esse fragment é
//encerrada e o estado do app volta para esse fragment
}
}
}
That is, since there is no good reason to call a method of a fragment that is not being used (since the current state of the app is in an Activity after the Fragment), we should not call a method from somewhere in the app that does not belong to the current state, instead, we must identify the exact moment that we return to the previous state and when necessary to use the necessary information of the state that has just been closed
Note
It is very important to show here that Fragment will not have reached the onActivityResult
method without the Activity that has this Fragment calling onActivityResult
of this Fragment. Example assuming FragmentA is within ActivityA:
Example - ActivityA:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
fragmentA.onActivityResult(requestCode,resultCode,data);
//É necessário fazer isso para que o fragmentA tenha seu método onActivityResult chamado
}
Hugs:)