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);
}
If you want to send data back to fragment class there can be a number of ways to do that:
First
Create a public method in fragment class
Call that method using the fragment object in activity class's onActivityResult()
Second
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With