0

I am currently using Firebase to upload an image into Firebase content in Android Studio. Once the file has successfully uploaded, I receive the url of the uploaded image using taskSnapshot.getDownloadUrl(). I want to then put this url in the Firebase Real-time database as a reference. I'm struggling to access the taskSnapshot.getDownloadUrl() from outside the onSuccess() method. Any ideas, please?

Faidz
  • 13
  • 4
  • 1
    why do you want to access it outside, can't you store to database inside `onSuccess`? – Peter Haddad Feb 18 '18 at 23:47
  • Please edit the question to include the [minimum code that reproduces where you're stuck](http://stackoverflow.com/help/mcve). Without that, the best I can do is point you to this great blog post that explains why you can't access the download URL outside of the `onSuccess()` method: https://medium.com/google-developers/why-are-firebase-apis-asynchronous-callbacks-promises-tasks-e037a6654a93 – Frank van Puffelen Feb 19 '18 at 00:17
  • you cant do this, what you need to do is concatenate the refferences and move your alertdialog, since the database is in realtime , the downloadurl could change at anytime, and storing that value inside a variable it will not change asynchronous and you could get a nullpointerexecption trying to reach something that has changed. – Gastón Saillén Feb 19 '18 at 02:02
  • Possible duplicate of [Firestore - object with inner Object](https://stackoverflow.com/questions/48499310/firestore-object-with-inner-object) – Alex Mamo Feb 19 '18 at 08:49

2 Answers2

1

I understand that you want to put the uploaded image URL into Firebase Database.

What you can do is, Declare a global variable of type String

private String imageUrl;

Then get the url of image inside onSuccess() method and store in the string

imageUrl = taskSnapshot.getDownloadUrl().toString();

then after the image is uploaded, you have the image URL as string, so just push it to database like this

DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("ImageUrl").setValue(imageUrl);
0
# declare variable like below:
    String Storage_Path = "Image_Uploads/";
    String Database_Path = "All_Image_Uploads_Database";
 # declare firebase storage or real time database  variable like below : 
    StorageReference myrefrence;
    DatabaseReference databaseReference;

  myrefrence = FirebaseStorage.getInstance().getReference();     
        databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path);

 public void UploadImageFileToFirebaseStorage(Uri FilePathUri) {
        // Checking whether FilePathUri Is empty or not.
        if (FilePathUri != null) {
            // Setting progressDialog Title.
           // progressDialog.setTitle("Image is Uploading...");
            // Showing progressDialog.
           // progressDialog.show();
            // Creating second StorageReference.
            StorageReference storageReference2nd = myrefrence.child(Storage_Path + System.currentTimeMillis() + "." + GetFileExtension(FilePathUri));

            // Adding addOnSuccessListener to second StorageReference.
            storageReference2nd.putFile(FilePathUri)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            // Getting image name from EditText and store into string variable.
                            //String TempImageName = ImageName.getText().toString().trim();
                            // Hiding the progressDialog after done uploading.
                           // progressDialog.dismiss();
                            // Showing toast message after done uploading.
                            //Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();

                            @SuppressWarnings("VisibleForTests")
                            ImageUploadInfo imageUploadInfo = new ImageUploadInfo("",taskSnapshot.getDownloadUrl().toString());
                            // Getting image upload ID.
                            String ImageUploadId = databaseReference.push().getKey();
                            // Adding image upload id s child element into databaseReference.
                            databaseReference.child(ImageUploadId).setValue(imageUploadInfo);
                        }
                    })
                    // If something goes wrong .
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception exception) {
                            // Hiding the progressDialog.
                            //progressDialog.dismiss();
                            // Showing exception erro message.
                           // Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    })

                    // On progress change upload time.
                    .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                            // Setting progressDialog Title.
                            //progressDialog.setTitle("Image is Uploading...");
                        }
                    });
        } else {
            //Toast.makeText(MainActivity.this, "Please Select Image or Add Image Name", Toast.LENGTH_LONG).show();

        }
    }

    // Creating Method to get the selected image file Extension from File Path URI.
    public String GetFileExtension(Uri uri) {
        ContentResolver contentResolver = getContentResolver();
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        // Returning the file Extension.`enter code here`
        return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));

    }
Anil Atri
  • 68
  • 8
  • call it inside your method where you want to use it....(i think u call it inside OnActivityResult)UploadImageFileToFirebaseStorage(result);result is here imagepath that you return in onactivityresult. – Anil Atri Feb 19 '18 at 08:04