Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 400
Stepan Avatar asked Oct 25 '16 10:10

Stepan


1 Answers

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);
    }
}
like image 194
Sahil Avatar answered Oct 05 '22 09:10

Sahil