taskSnapshot.getDownloadUrl() method not working

后端 未结 23 756
有刺的猬
有刺的猬 2020-12-08 08:03
private void uploadImageToFirebaseStorage() {
    StorageReference profileImageRef =
        FirebaseStorage.getInstance().getReference(\"profilepics/\" + System.cur         


        
相关标签:
23条回答
  • 2020-12-08 08:56

    this is help help me with the last dependencies in 04/2020

         // Get a reference to store file at chat_photos/<FILENAME>
         final StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());
         photoRef.putFile(selectedImageUri).addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            //When the image has successfully uploaded, get its downloadURL
                            photoRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {
                                    Uri dlUri = uri;
                                    FriendlyMessage friendlyMessage = new 
                                      FriendlyMessage(null, mUsername, dlUri.toString());
    
    0 讨论(0)
  • 2020-12-08 08:59

    My Google Firebase Plugins in build.gradle(Module: app):

    implementation 'com.firebaseui:firebase-ui-database:3.3.1'
    implementation 'com.firebaseui:firebase-ui-auth:3.3.1'
    implementation 'com.google.firebase:firebase-core:16.0.0'
    implementation 'com.google.firebase:firebase-database:16.0.1'
    implementation 'com.google.firebase:firebase-auth:16.0.1'
    implementation 'com.google.firebase:firebase-storage:16.0.1'
    

    build.gradle(Project):

     classpath 'com.google.gms:google-services:3.2.1'
    

    My upload() function and fetching uploaded data from Firebase storage :

    private void upload() {
        if (filePath!=null) {
            final ProgressDialog progressDialog = new ProgressDialog(this);
            progressDialog.setTitle("Uploading...");
            progressDialog.show();
    
            final StorageReference ref = storageReference.child(new StringBuilder("images/").append(UUID.randomUUID().toString()).toString());
            uploadTask = ref.putFile(filePath);
    
            Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                @Override
                public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                    if (!task.isSuccessful()) {
                        throw task.getException();
                    }
    
                    return ref.getDownloadUrl();
                }
            }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                @Override
                public void onComplete(@NonNull Task<Uri> task) {
                    if (task.isSuccessful()) {
                        Uri downloadUri = task.getResult();
                        progressDialog.dismiss();
                        // Continue with the task to get the download URL
                        saveUrlToCategory(downloadUri.toString(),categoryIdSelect);
                    } else {
                        Toast.makeText(UploadWallpaper.this, "Fail UPLOAD", Toast.LENGTH_SHORT).show();
                    }
                }
            }).addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override
                public void onSuccess(Uri uri) {
                    progressDialog.setMessage("Uploaded: ");
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    progressDialog.dismiss();
                    Toast.makeText(UploadWallpaper.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
    

    FOR THOSE WHO ARE USING LATEST FIREBASE VERSION taskSnapshot.getDownloadUrl() method is DEPRECATED or OBSOLETE !!

    0 讨论(0)
  • 2020-12-08 09:01
    //upload button onClick
    public void uploadImage(View view){
        openImage()
    }
    
    private Uri imageUri;
    
    ProgressDialog pd;
    
    //Call open Image from any onClick Listener
    private void openImage() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent,IMAGE_REQUEST);
    }
    
    private void uploadImage(){
        pd = new ProgressDialog(mContext);
        pd.setMessage("Uploading...");
        pd.show();
    
        if (imageUri != null){
            final StorageReference fileReference = storageReference.child(userID
                    + "."+"jpg");
    
            // Get the data from an ImageView as bytes
            _profilePicture.setDrawingCacheEnabled(true);
            _profilePicture.buildDrawingCache();
    
            //Bitmap bitmap = ((BitmapDrawable) _profilePicture.getDrawable()).getBitmap();
    
            Bitmap bitmap = null;
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
            byte[] data = baos.toByteArray();
    
            UploadTask uploadTask = fileReference.putBytes(data);
            uploadTask.addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    // Handle unsuccessful uploads
                    pd.dismiss();
                    Log.e("Data Upload: ", "Failled");
                }
            }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    // taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc.
                    // ...
                    Log.e("Data Upload: ", "success");
                    Task<Uri> result = taskSnapshot.getMetadata().getReference().getDownloadUrl();
                    result.addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {
                            String downloadLink = uri.toString();
                            Log.e("download url : ", downloadLink);
                        }
                    });
    
                    pd.dismiss();
    
                }
            });
    
        }else {
            Toast.makeText(getApplicationContext(),"No Image Selected", Toast.LENGTH_SHORT).show();
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    
        Bitmap bitmap = null;
        if (requestCode == IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
            imageUri = data.getData();
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),imageUri);
                _profilePicture1.setImageBitmap(bitmap);
                _profilePicture1.setDrawingCacheEnabled(true);
                _profilePicture1.buildDrawingCache();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            if (uploadTask != null && uploadTask.isInProgress()){
                Toast.makeText(mContext,"Upload in Progress!", Toast.LENGTH_SHORT).show();
            }
            else {
                try{
                    uploadImage();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-08 09:02
    taskSnapshot.**getDownloadUrl**().toString(); //deprecated and removed
    

    use below code for downloading Url

    final StorageReference profileImageRef= FirebaseStorage.getInstance().getReference("profilepics/" + "abc_10123" + ".jpg");
    
    profileImageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
            {
                @Override
                public void onSuccess(Uri downloadUrl) 
                {                
                   //do something with downloadurl
                } 
            });
    
    0 讨论(0)
  • 2020-12-08 09:04

    I'm using Firebase Storage API version 16.0.5 and the task has to be referenced as

     someTask.getResult().getMetadata().getReference().getDownloadUrl().toString();
    

    hope this helps!

    0 讨论(0)
提交回复
热议问题