File upload to firebase storage fails, java security exception, permission denied

Issue

I am trying to write a simple function to register a user to firebase and upload his profile picture to firebase storage.

The code I currently have:

public static void createNewUser(String email, String username, String password, @Nullable Uri profileImage) {
        auth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(authTask -> {
            if (authTask.isSuccessful()) {
                assert auth.getCurrentUser() != null;
                String uid = auth.getCurrentUser().getUid();

                StorageReference storageReference = storage.getReference("profileImages/" + uid);
                if (profileImage != null)
                    storageReference.putFile(profileImage);
            }
            else throw new RuntimeException("Error creating user!");
        });
    }

The Uri is retrieved with the following code:(The Uri is a path to a image in device storage)

ActivityResultLauncher<String> contentGetter = registerForActivityResult(new ActivityResultContracts.GetContent(), uri -> {
            profileImage.setImageURI(uri);
            this.profileImageUri = uri;
        });
contentGetter.launch("image/*");

NOTE: the error is thrown from "storageReference.putFile(profileImage);"

When I run this code I get the following error:

java.lang.SecurityException: Permission Denial: opening provider com.android.providers.media.MediaDocumentsProvider from ProcessRecord{fcb00f2 10396:com.mediamania/u0a146} (pid=10396, uid=10146) requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs

My current premissions:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Any idea what causes this?

Solution

Found the error, I was using the wrong intent in the file chooser, here’s the code snippet:

ActivityResultLauncher<Intent> chooserLauncher = registerForActivityResult(
    new ActivityResultContracts.StartActivityForResult(),
    result -> {
        if (result.getResultCode() != Activity.RESULT_OK)
            throw new RuntimeException("Error choosing image!");

        Intent data = result.getData();
        // Process result
    }
);

// Configure chooser
Intent chooser = new Intent(Intent.ACTION_OPEN_DOCUMENT);
chooser.addCategory(Intent.CATEGORY_OPENABLE);
chooser.setType("image/*");

Answered By – niv shalom

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published