How to pass variable to onActivityResult() from populateViewHolder?

390 Views Asked by At

I have a Firebase Recycler View which contains a button like this

final String post_key = getRef(position).getKey();

viewHolder.btnUpload.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {


                                Intent data = new Intent();

                                data.putExtra("post_key",post_key);
                                Log.d("post_key", data.getExtras().getString("post_key"));

                                data.setType("image/*");
                                data.setAction(Intent.ACTION_GET_CONTENT);
                                startActivityForResult(data, GALLERY_REQUEST);


                            }
                        });

This will trigger an action in OnActivityResult(). I was trying to access the variable "post_key" in OnActivityResult. Therefore, I put it to the extra, and call the getString function in OnActivityResult.

final String post_key=data.getExtras().getString("post_key");

However, the app crashed and keeps telling me that I attempt to invoke virtual method 'getString' on a null object reference

2

There are 2 best solutions below

0
On

You need to check the request code and the result code as well:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == GALLERY_REQUEST) {
        if (resultCode == Activity.RESULT_OK) {
            // here you can access the intent
            String msg = (data != null) ? data.getStringExtra("post_key") : "";
            Log.d("post_key", "Got post_key: " + msg);
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}
0
On

You can not send your data to another app - if it does not accept. The thing you are doing is not mentioned anywhere.

Correct Way

in onClick don't pass extra, and hold your post_key in your activity/ adapter.

adapter.setPostKey(post_key);

Then in onActivityResult() get this post_key.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == GALLERY_REQUEST) {
        if (resultCode == Activity.RESULT_OK) {
            String post_key = adapter.getPostKey();
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}