Search code examples
javaandroidandroid-fragmentsinterfaceonactivityresult

How to get callback from activity back to fragment using interface


I have a fragment, where I have a button to choose an image from a gallery. The gallery is open successfully, but when I choose the image, I do not get the result from activity. So I consider to use a callback (interface). However, I do know how.

Could you suggest me something please?

interface

public interface CallbackListener {
    void onPhotoTake(String url);
}

in fragment click

@OnClick(R.id.addPhoto) void photo() {
        if (isStoragePermissionGranted()) {
            Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            context.startActivityForResult(i, RESULT_LOAD_IMAGE);
        }
}

activity

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
}
  • here I would like to send result back to fragment using interface

Solution

  • If you want to send data back to fragment class there can be a number of ways to do that:

    First

    1. Create a public method in fragment class

    2. Call that method using the fragment object in activity class's onActivityResult()


    Second

    1. Create an interface in activity and implement that interface in fragment. Then with the help of interface, send your data to fragment e.g.

    Activity class

    DataReceivedListener listener;
    
    public void setDataReceivedListener(DataReceivedListener listener) {
        this.listener = listener;
    }
    
    public interface DataReceivedListener {
        void onReceived(int requestCode, int resultCode, Intent data)
    }
    

    Fragment Class

    class fragment extends Fragments implements yourActivityClassName.DataReceivedListener {
        @Override
        void onReceived(int requestCode, int resultCode, Intent data) {
    
        }
    
        onViewCreated(...) {
            ((yourActivityName) getActivity()).setDataReceivedListener(this);
        }
    }
    

    in Acitivity class

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (listener != null) {
            listener.onActivityResult(requestCode, resultCode, data);
        }
    }