Passing data through intent for onActivityResult

Im trying to save a pdf file on a user-picked location but Im having problems passing data through the intent.

I tried using a bundle to pass the info but it is always null.
It only works if I add a local variable and assign it in the @save method. But I want to pass it through the intent.

The thing is im not going into another activity, just to choose a directory and im coming back.

`protected void save(byte[] bytes, String fileName, String mimeType) {

    Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
    intent.setType(mimeType);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.putExtra(Intent.EXTRA_TITLE, fileName);
    intent.putExtra("bytes", bytes);

    activityResultLaunch.launch(intent);
}`

`ActivityResultLauncher<Intent> activityResultLaunch = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {

                Intent data = result.getData();
                try {
                    Uri uri = data.getData();
                    OutputStream outputStream =   getContext().getContentResolver().openOutputStream(uri);
                    
                    // here it is always null
                    //byte[] bytes = data.getByteArrayExtra("bytes");

                    outputStream.write(bytes);
                    outputStream.close();

                    Toast.makeText(getContext(), "Successfully saved document to device!", Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
                    Toast.makeText(getContext(), "Failed to save document to device.", Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
            }
        });`

Any suggestions? I dont see what im missing here, ive been banging my head on this for a couple of hours and couldnt get it to work. Any help is greatly appreciated!

>Solution :

    intent.putExtra("bytes", bytes);

Here, you are passing an Intent extra to the activity that you are starting. That activity is a device-supplied activity that responds to ACTION_CREATE_DOCUMENT.

More importantly, it is not your activity. It is certainly not the activity that is calling launch() for that Intent.

So, that bytes extra will be available to the ACTION_OPEN_DOCUMENT activity. That activity will ignore that extra. It will not include that extra in the completely different Intent that is delivered to your onActivityResult() method.

But I want to pass it through the intent.

That is not an option in Android, sorry.

Leave a Reply