How to pass data from current fragment to previous fragment
This method is also called the Delegate Pattern
• Create an interface with one method like this one:
public interface FragmentCallback {
void onDataSent(String yourData);
}
• Implement this interface in your FragmentA and implement onDataSent() method:
public class FragmentA implements FragmentCallback {
@Override
void onDataSent(String yourData){
//Do something with your data
}
}
• Declare this interface variable in Fragment B and create a public setter method:
public class FragmentB {
private FragmentCallback fragmentCallback;
public void setFragmentCallback(FragmentCallback callback) {
this.fragmentCallback = callback;
}
}
• Somewhere withing FragmentA set it as a callback on FragmentB instance:
fragmentB.setFragmentCallback(this);
• Path data from FragmentB to FragmentA (you can do it from one of fragment's lifecycle method if data should be sent when FragmentB is about to be closed):
public class FragmentB {
public void onDestroy() {
if(fragmentCallback != null){
fragmentCallback.onDataSent("Some data from FragmentB");
}
super.onDestroy();
}
}