0

I have a problem adding a photo to Firebase Storage. Here is all my code :

    @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_settings, container, false);

    firebaseAuth = FirebaseAuth.getInstance();
    firebaseUser = firebaseAuth.getCurrentUser();
    firebaseFirestore = FirebaseFirestore.getInstance();
    firebaseStorage = FirebaseStorage.getInstance();
    storageReference = firebaseStorage.getReference();


    profileImage = (ImageView) view.findViewById(R.id.ivProfilePicture);
    logout = (Button) view.findViewById(R.id.btLogout);
    deleteAccount = (Button) view.findViewById(R.id.btDelete);
    updateAccount = (Button) view.findViewById(R.id.btUpdate);
    searchPicture = (Button) view.findViewById(R.id.btSelect);
    addPicture = (Button) view.findViewById(R.id.btUpload);
    pseudo = (TextView) view.findViewById(R.id.tvUserPseudo);
    name = (EditText) view.findViewById(R.id.etUserNameModif);
    surname = (EditText) view.findViewById(R.id.etUserSurnameModif);
    mail = (TextView) view.findViewById(R.id.tvUserEmail);
    age = (EditText) view.findViewById(R.id.etUserAgeModif);

    modifyMail = (TextView) view.findViewById(R.id.tvChangeEmail);
    modifyPassword = (TextView) view.findViewById(R.id.tvChangePassword);

    userMail = firebaseUser.getEmail();

    progressDialog = new ProgressDialog(view.getContext(), R.style.AppCompatAlertDialogStyle);

    userUid = FirebaseAuth.getInstance().getCurrentUser().getUid();                             // Collect user data
    documentReference = firebaseFirestore.collection("Users").document(userUid);
    documentReference.addSnapshotListener(getActivity(), new EventListener<DocumentSnapshot>() {// Display data in TextView
        @Override
        public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
            if (e == null) {
                if (documentSnapshot.exists()) {
                    pseudo.setText(documentSnapshot.getString("Pseudo"));
                    name.setText(documentSnapshot.getString("Name"));
                    surname.setText(documentSnapshot.getString("Surname"));
                    mail.setText(userMail);
                    age.setText(documentSnapshot.getString("Age"));
                } else {

                }
            }
        }
    });

    modifyMail.setOnClickListener(new View.OnClickListener() {                                  // Change Email
        @Override
        public void onClick(View view) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.MyAlertDialogStyle);
            builder.setTitle("Pour modifier l'adresse e-mail merci de vous reconnecter :");

            final View customLayout = getLayoutInflater().inflate(R.layout.alertdialog_email, null);
            builder.setView(customLayout);

            builder.setPositiveButton("Valider", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    EditText mailchange = customLayout.findViewById(R.id.etMailChange);
                    EditText passwordchange = customLayout.findViewById(R.id.etPasswordChange);
                    EditText newmailchange = customLayout.findViewById(R.id.etNewMail);
                    String mailc = mailchange.getText().toString();
                    String passwordc = passwordchange.getText().toString();
                    String newmailc = newmailchange.getText().toString();

                    if (!mailc.isEmpty() && !passwordc.isEmpty() && !newmailc.isEmpty()) {
                        firebaseAuth.fetchSignInMethodsForEmail(newmailc)                       // Check if an account already exist with this E-mail
                                .addOnCompleteListener(task -> {

                                    if (mailc.matches(emailPattern) && newmailc.matches(emailPattern)) {
                                        List<String> check = task.getResult().getSignInMethods();
                                        if (check.isEmpty()) {
                                            result = true;
                                        }
                                        if (!check.isEmpty()) {
                                            Toast.makeText(getActivity(), "Un compte existe déjà avec cet E-mail", Toast.LENGTH_SHORT).show();
                                            dialog.dismiss();
                                            result = false;
                                        }
                                    } else {
                                        Toast.makeText(getActivity(), "Merci de rentrer une adresse E-mail valide", Toast.LENGTH_SHORT).show();
                                        dialog.dismiss();
                                        result = false;
                                    }

                                });
                    } else {
                        Toast.makeText(getActivity(), "Veuillez remplir tous les champs", Toast.LENGTH_SHORT).show();
                        result = false;
                    }

                    if (result == true) {
                        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

                        AuthCredential credential = EmailAuthProvider
                                .getCredential(mailc, passwordc);
                        user.reauthenticate(credential)
                                .addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {

                                        if (task.isSuccessful()) {
                                            FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
                                            user.updateEmail(newmailc);

                                            sendEmailVerification();
                                        } else {
                                            Toast.makeText(getActivity(), "E-mail ou mot de passe incorrect", Toast.LENGTH_SHORT).show();
                                        }

                                    }
                                });
                    }

                }
            });

            builder.setNeutralButton("Annuler", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            AlertDialog dialog = builder.create();
            dialog.show();
        }

    });

    modifyPassword.setOnClickListener(new View.OnClickListener() {                              // Change password
        @Override
        public void onClick(View view) {
            String useremail = mail.getText().toString().trim();

            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.MyAlertDialogStyle);
            builder.setTitle("Voulez-vous vraiment modifier le mot de passe ?");

            builder.setPositiveButton("Oui, envoyer le mail", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    firebaseAuth.sendPasswordResetEmail(useremail).addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            if (task.isSuccessful()) {
                                getActivity().finish();
                                Intent intent = new Intent(getActivity(), ConnectionActivity.class);
                                getActivity().startActivity(intent);
                                Toast.makeText(getActivity(), "E-mail de réinitialisation envoyé !", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
            });

            builder.setNeutralButton("Non, annuler", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            AlertDialog dialog = builder.create();
            dialog.show();

        }
    });

    updateAccount.setOnClickListener(new View.OnClickListener() {                               // Modify information's
        @Override
        public void onClick(View view) {
            nameModif = name.getText().toString();
            surnameModif = surname.getText().toString();
            ageModif = age.getText().toString();

            Map<String, Object> user = new HashMap<>();
            user.put("Name", nameModif);
            user.put("Surname", surnameModif);
            user.put("Age", ageModif);

            documentReference.update(user);

            Toast.makeText(getActivity(), "Informations modifiées avec succès !", Toast.LENGTH_SHORT).show();
        }
    });

    logout.setOnClickListener(new View.OnClickListener() {                                      // Logout
        @Override
        public void onClick(View view) {
            firebaseAuth.signOut();
            getActivity().finish();
            Intent intent = new Intent(getActivity(), ConnectionActivity.class);
            getActivity().startActivity(intent);
            Toast.makeText(getActivity(), "Déconnexion réussie", Toast.LENGTH_SHORT).show();
        }
    });

    searchPicture.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startCropActivity();
        }
    });

    addPicture.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            addPictureFirebase();
        }
    });

    deleteAccount.setOnClickListener(new View.OnClickListener() {                               // Delete an account
        @Override
        public void onClick(View view) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(view.getContext());
            dialog.setTitle("Êtes-vous sur ?");
            dialog.setMessage("Supprimer ce compte sera définitif et vous ne pourrez plus revenir en arrière.");
            dialog.setPositiveButton("Supprimer", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    progressDialog.setMessage("Suppression du compte en cours");
                    progressDialog.show();
                    firebaseUser.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            if (task.isSuccessful()) {
                                Toast.makeText(getActivity(), "Compte supprimer avec succès", Toast.LENGTH_SHORT).show();
                                progressDialog.dismiss();
                                getActivity().finish();
                                Intent intent = new Intent(getActivity(), ConnectionActivity.class);
                                getActivity().startActivity(intent);
                            } else {
                                Toast.makeText(getActivity(), "Une erreur est survenue", Toast.LENGTH_SHORT).show();
                                progressDialog.dismiss();
                            }
                        }
                    });
                }
            });

            dialog.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                }
            });

            AlertDialog alertDialog = dialog.create();
            alertDialog.show();

        }
    });

    return view;

}

private void sendEmailVerification() {                                                          // Send verification E-mail to user mail address
    if (firebaseUser != null) {
        firebaseUser.sendEmailVerification().addOnCompleteListener(task -> {
            if (task.isSuccessful()) {
                Toast.makeText(getActivity(), "E-mail modifiée avec succès, un mail de vérification a été envoyé ", Toast.LENGTH_SHORT).show();
                firebaseAuth.signOut();
                getActivity().finish();
                Intent intent = new Intent(getActivity(), ConnectionActivity.class);
                getActivity().startActivity(intent);
            } else {
                Toast.makeText(getActivity(), "Le mail de vérification n'a pas pu être envoyé", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

private void startCropActivity() {                                                              // Different possibilities to choose a photo
    CropImage.activity()
            .start(getContext(), this);
}

@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {          // Crop selected photo
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
        CropImage.ActivityResult result = CropImage.getActivityResult(data);
        if (resultCode == RESULT_OK) {
            Uri resultUri = result.getUri();
            profileImage.setImageURI(resultUri);
        } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
            Exception error = result.getError();
        }
    }
}

private void addPictureFirebase() {                                                             // Add photo to storage
    StorageReference profileImagesRef = storageReference.child("profileImages/" + userUid);

    storageReference.getName().equals(profileImagesRef.getName());

    if (resultUri == null) {
        Toast.makeText(getActivity(), "Sélectionner d'abord une photo"+resultUri, Toast.LENGTH_SHORT).show();
    } else {
        storageReference.putFile(resultUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Toast.makeText(getActivity(), "Photo envoyée avec succès !", Toast.LENGTH_SHORT).show();
            }
        });
        storageReference.putFile(resultUri).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(getActivity(), "Erreur", Toast.LENGTH_SHORT).show();
            }
        });
    }

}

And now the part of the code that interests us here :

@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {          // Crop selected photo
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
        CropImage.ActivityResult result = CropImage.getActivityResult(data);
        if (resultCode == RESULT_OK) {
            Uri resultUri = result.getUri();
            profileImage.setImageURI(resultUri);
        } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
            Exception error = result.getError();
        }
    }
}

private void addPictureFirebase() {                                                             // Add photo to storage
    StorageReference profileImagesRef = storageReference.child("profileImages/" + userUid);

    storageReference.getName().equals(profileImagesRef.getName());

    if (resultUri == null) {
        Toast.makeText(getActivity(), "Sélectionner d'abord une photo"+resultUri, Toast.LENGTH_SHORT).show();
    } else {
        storageReference.putFile(resultUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Toast.makeText(getActivity(), "Photo envoyée avec succès !", Toast.LENGTH_SHORT).show();
            }
        });
        storageReference.putFile(resultUri).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(getActivity(), "Erreur", Toast.LENGTH_SHORT).show();
            }
        });
    }

}

The problem is therefore that in addPictureFirebase() the resultUri value is always considered null. What I can not solve because if I display this value before entering the addPictureFirebase() method, it is not null. It is even totally correct but the moment I try to retrieve it in the second method it becomes null.

I have tried several solutions but nothing works so far so I come to seek help.

1
  • If you encounter problems, it's best to create a MCVE when posting a question. You posted almost 400 lines of code for this issue. That's a lot for people to parse and try to debug online. Please edit your question and isolate the problem, in that way you increase your chances of being helped. Commented Feb 1, 2021 at 12:06

1 Answer 1

0

As much as I can see your resultUri is a local variable inside onActivityResult, that's why it is not visible inside addPictureFirebase(). I am not even sure how it isn't red for you since I don't see it declared anywhere else.

Create global variable above onCreate

Uri resultUri;

then in your onActivityResult use this:

resultUri = result.getUri();

then it should work in addPictureFirebase().

Sign up to request clarification or add additional context in comments.

1 Comment

It work ! I'm sooo stupid. But now it always comes out of the loop with the part onFailureListener, thank's for your help.