Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onActivityResult inside a RecyclerView.Adapter not being used

I have a button inside an Adapter which goes into gallery:

    MyAdapter extends
            RecyclerView.Adapter<RecyclerView.ViewHolder> {
    ...
    onClic..{
        Intent intent = new Intent(
                                    Intent.ACTION_PICK,
                                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            intent.setType("image/*");
                            ((Activity) context).startActivityForResult(
                                    Intent.createChooser(intent, "Select File"),
                                    SELECT_FILE);}
    ....
 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
        }
    }
..
    }

What I'm trying to do is to update an ImageView with the image selected from the gallery, but in order to do that I have to use onActivityResult and the compiler is complaining method onActivityResult is never used and cannot resolve method onActivityResult.

How can I go about this ?

like image 496
Bogdan Daniel Avatar asked Feb 06 '16 16:02

Bogdan Daniel


1 Answers

Note on this line you are using an Activity to call startActivityForResult:

((Activity) context).startActivityForResult();

onActivityResult(...) is a callback method and should be in the same Activity you used to call startActivityForResult().

You are getting the compiler error because there is no such method to override named onActivityResult(...) for RecyclerView.Adapter.

EDIT:

Since you asked how you can do this properly here is one option.

Add the following interface to MyAdapter:

public interface OnClickImageListener{
    void onClick();
}

Then have your dialog implement that interface. In the onClick method do:

@Override
public void onClick() {
    Intent intent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    intent.setType("image/*");
    startActivityForResult(
           Intent.createChooser(intent, "Select File"), SELECT_FILE);
}

You can add the onActivityResult(...) method to your Fragment and it will now be called.

To use this when you create MyAdapter pass the Fragment in as an argument to the constructor and reference it as a OnClickImageListener so your click listener in the adapter simply becomes:

imageClickListener.onClick();

Also note you can add an index to the onClick() method or whatever else you need to know which item in the adapter to populate the image with once it is returned.

like image 168
George Mulligan Avatar answered Sep 18 '22 02:09

George Mulligan