Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UploadTask.TaskSnapshot doesn't have getDownloadUrl() method #41

Open
mfgabriel92 opened this issue May 29, 2018 · 41 comments
Open

UploadTask.TaskSnapshot doesn't have getDownloadUrl() method #41

mfgabriel92 opened this issue May 29, 2018 · 41 comments

Comments

@mfgabriel92
Copy link

I'm following a tutorial teaching how to upload images to Firebase. At certain moment the instructor will write the code to get the download URL after uploading by using getDownloadUrl() method from UploadTask.TaskSnapshot, but for me, this method doesn't exist.

enter image description here

Based on another code I found, I tried the following:

OnSuccessListener<UploadTask.TaskSnapshot> upload = new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
        ChatroomMessage message = new ChatroomMessage(null, mUsername, taskSnapshot.getDownloadUrl());
        mMessagesDatabaseReference.push().setValue(message);
    }
};

Because it is similar to what's shown in the documentation, but I didn't understand it very well. How to implement it?

@LucaUburti
Copy link

LucaUburti commented May 31, 2018

Yes they deprecated and then removed that method.
I use the following code, similar to what is written in the docs.

photoStorageReference.putFile(selectedImageUri).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 photoStorageReference.getDownloadUrl();
    }
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
    @Override
    public void onComplete(@NonNull Task<Uri> task) {
        if (task.isSuccessful()) {
            Uri downloadUri = task.getResult();
            FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUri.toString());
            mMessagesDatabaseReference.push().setValue(friendlyMessage);
        } else {
            Toast.makeText(MainActivity.this, "upload failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
});

@developcodeza-matthew
Copy link

Have a look here.

Its as simple as using your storageRef to get the download url on condition the task was successfull.

      OnSuccessListener<UploadTask.TaskSnapshot> upload = new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                ChatroomMessage message = new ChatroomMessage(null, mUsername, ref.getDownloadUrl());
                mMessagesDatabaseReference.push().setValue(message);
            }
        };

Note the

    ref.getDownloadUrl() 

In place of

    taskSnapshot.getDownloadUrl() 

@darkokoa
Copy link

darkokoa commented Jun 16, 2018

Try this

@OverRide
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
FriendlyMessage message = new FriendlyMessage(null, mUsername
, taskSnapshot.getStorage().getDownloadUrl().toString());
mMessagesDatabaseReference.push().setValue(message);
}

// FriendlyMessage(), the third parameter
taskSnapshot.getStorage().getDownloadUrl().toString()

I try to do it like this ↓↓↓ can work. Thanks @Parthav46

Uri uri = data.getData();
    if (uri != null) {
        final StorageReference imgReference = mChatPhotosStorageReference.child(uri.getLastPathSegment());
        UploadTask uploadTask = imgReference.putFile(uri);

        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 imgReference.getDownloadUrl();
                }
            }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                @Override
                public void onComplete(@NonNull Task<Uri> task) {
                    if (task.isSuccessful()) {
                        Uri taskResult = task.getResult();
                        FriendlyMessage message = new FriendlyMessage(null, mUsername, taskResult.toString());
                        mMessagesDatabaseReference.push().setValue(message);
                    }
                }
            });
        }

@Parthav46
Copy link

Parthav46 commented Jun 18, 2018

taskSnapshot.getStorage().getDownloadUrl().toString()

@DevRyz3n running this command would raise FileNotFoundException as the returned value is not the download url for file.
Instead try this code where I have created a Task object to perform getDownloadUrl() task, waited for its completion in the main thread and then obtained the URL through getResult() function.

@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
     Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
     while (!urlTask.isSuccessful());
     Uri downloadUrl = urlTask.getResult();
     FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUrl.toString());
     mDatabaseReference.push().setValue(friendlyMessage);
}

@kickass23
Copy link

i am currently having the same problem

public class FirebaseStorageHelper {

private static final String TAG = FirebaseStorageHelper.class.getCanonicalName();

private FirebaseStorage firebaseStorage;

private StorageReference rootRef;

private Context context;

public FirebaseStorageHelper(Context context){
    this.context = context;
    init();
}

private void init(){
    this.firebaseStorage = FirebaseStorage.getInstance();
    rootRef = firebaseStorage.getReferenceFromUrl("gs://fir-analyticexample.appspot.com");
}

public void saveProfileImageToCloud(String userId, Uri selectedImageUri, final ImageView imageView) {

    StorageReference photoParentRef = rootRef.child(userId);
    StorageReference photoRef = photoParentRef.child(selectedImageUri.getLastPathSegment());
    UploadTask uploadTask = photoRef.putFile(selectedImageUri);

    uploadTask.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.d(TAG, "OnFailure " + e.getMessage());
        }
    }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            @SuppressWarnings("VisibleForTests") Uri downloadUrl = taskSnapshot.getDownloadUrl();
            Glide.with(context).load(downloadUrl.getPath()).into(imageView);
        }
    });

}

}

@sabiou
Copy link

sabiou commented Jul 9, 2018

Hello @mfgabriel92 does it work? I mean when you changed the onSucces() implementation?

@achyutghosh
Copy link

`
package com.google.firebase.udacity.friendlychat;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.firebase.ui.auth.AuthUI;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";

public static final String ANONYMOUS = "anonymous";
public static final int DEFAULT_MSG_LENGTH_LIMIT = 1000;
public static final int RC_SIGN_IN = 1;
// Integer constant for startActivityResult
private static final int RC_PHOTO_PICKER = 2;



private ListView mMessageListView;
private MessageAdapter mMessageAdapter;
private ProgressBar mProgressBar;
private ImageButton mPhotoPickerButton;
private EditText mMessageEditText;
private Button mSendButton;


private String mUsername;



// Firebase instance variables
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mMessagesDatabaseReference;
private ChildEventListener mChildEventListener;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private FirebaseStorage mFirebaseStorage;
private StorageReference mChatPhotosStorageReference;



@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mUsername = ANONYMOUS;

    // Initialize Firebase components
    mFirebaseDatabase = FirebaseDatabase.getInstance();
    mFirebaseAuth = FirebaseAuth.getInstance();
    mFirebaseStorage = FirebaseStorage.getInstance();

    mMessagesDatabaseReference = mFirebaseDatabase.getReference().child("messages");
    mChatPhotosStorageReference = mFirebaseStorage.getReference().child("chat_photos"); // chat_photos is the folder name in firebase consol

    // Initialize references to views
    mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
    mMessageListView = (ListView) findViewById(R.id.messageListView);
    mPhotoPickerButton = (ImageButton) findViewById(R.id.photoPickerButton);
    mMessageEditText = (EditText) findViewById(R.id.messageEditText);
    mSendButton = (Button) findViewById(R.id.sendButton);

    // Initialize message ListView and its adapter
    List<FriendlyMessage> friendlyMessages = new ArrayList<>();
    mMessageAdapter = new MessageAdapter(this, R.layout.item_message, friendlyMessages);
    mMessageListView.setAdapter(mMessageAdapter);

    // Initialize progress bar
    mProgressBar.setVisibility(ProgressBar.INVISIBLE);

    // ImagePickerButton shows an image picker to upload a image for a message
    mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Fire an intent to show an image picker
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/jpeg");
            intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
            startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
        }
    });



    // Enable Send button when there's text to send
    mMessageEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }



        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (charSequence.toString().trim().length() > 0) {
                mSendButton.setEnabled(true);
            } else {
                mSendButton.setEnabled(false);
            }
        }


        @Override
        public void afterTextChanged(Editable editable) {
        }
    });

    mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(DEFAULT_MSG_LENGTH_LIMIT)});


    // Send button sends a message and clears the EditText
    mSendButton.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View view) {
            FriendlyMessage friendlyMessage = new FriendlyMessage(mMessageEditText.getText().toString(), mUsername, null);
            mMessagesDatabaseReference.push().setValue(friendlyMessage);
            // Clear input box
            mMessageEditText.setText("");
        }

    });



    mAuthStateListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                onSignedInInitialize(user.getDisplayName());
            } else {
                // User is signed out
                onSignedOutCleanup();
                //Source https://github.com/firebase/FirebaseUI-Android
                startActivityForResult(
                        AuthUI.getInstance()
                                .createSignInIntentBuilder()
                                .setIsSmartLockEnabled(false)
                                .setAvailableProviders(Arrays.asList(
                                        new AuthUI.IdpConfig.GoogleBuilder().build(),
                                        new AuthUI.IdpConfig.EmailBuilder().build()))
                                .build(),
                        RC_SIGN_IN);
            }
        }

    };
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_SIGN_IN) {
        // Sign_in succeeded, set up the UI
        Toast.makeText(this, "Siggned in!", Toast.LENGTH_SHORT).show();
    } else if (resultCode == RESULT_CANCELED) {
        // Sign in was canceled by the user, finish the activity
        Toast.makeText(this, "Sign in canceled", Toast.LENGTH_SHORT).show();
        finish();
    } else if (requestCode == RC_PHOTO_PICKER && requestCode == RESULT_OK) {
        Uri selectedimageUri = data.getData();

        // Get a reference to store file at chat_photos/<FILENAME>
        final StorageReference photoRef =
                mChatPhotosStorageReference.child(selectedimageUri.getLastPathSegment());

        // TODO Not working, method depricated
        // Upload file to Firebase Storage
        photoRef.putFile(selectedimageUri).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 photoRef.getDownloadUrl();
            }
        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                if (task.isSuccessful()) {
                    // When the image has successfully uploaded, we get its download URL
                    Uri downloadUri = task.getResult();

                    // Set the download URL to the message box, so that the user can send it to the database
                    FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUri.toString());
                    mMessagesDatabaseReference.push().setValue(friendlyMessage);
                } else {
                    Toast.makeText(MainActivity.this, "upload failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
}

@Override
protected void onResume() {
    super.onResume();
    mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}



@Override

protected void onPause() {
    super.onPause();
    if (mAuthStateListener != null) {
        mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
    }

    mMessageAdapter.clear();
    detachDatabaseReadListener();
}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_menu, menu);
    return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
        case R.id.sign_out_menu:
            // sign out
            AuthUI.getInstance().signOut(this);
            return true;
         default:
             return super.onOptionsItemSelected(item);
    }
}



private void onSignedInInitialize(String username) {
    mUsername = username;
    attachDatabaseReadListener();
}



private void onSignedOutCleanup() {
    mUsername = ANONYMOUS;
    mMessageAdapter.clear();
    detachDatabaseReadListener();
}



private void attachDatabaseReadListener() {
    if (mChildEventListener == null) {
        mChildEventListener = new ChildEventListener() {

            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                FriendlyMessage friendlyMessage = dataSnapshot.getValue(FriendlyMessage.class);
                mMessageAdapter.add(friendlyMessage);
            }

            public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
            public void onChildRemoved(DataSnapshot dataSnapshot) {}
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
            public void onCancelled(DatabaseError databaseError) {}
        };

        mMessagesDatabaseReference.addChildEventListener(mChildEventListener);
    }
}



private void detachDatabaseReadListener() {
    if (mChildEventListener != null) {
        mMessagesDatabaseReference.removeEventListener(mChildEventListener);
        mChildEventListener = null;
    }
}

}`

I use this code. but it does not store the photos in firebase. Not showing anything, but the app is not crashed. Help me to fix this.

@lantosgyuri
Copy link

@achyutghosh
else if (requestCode == RC_PHOTO_PICKER && requestCode == RESULT_OK)

You should write resultCode

@kamrul4248hasan
Copy link

How can i thumb the using your procedure and using continuWithtask() ?? Can you help me ?

@kamrul4248hasan
Copy link

How can i thumb the using your procedure and using continuWithtask() ?? Can you help me ?
https://github.com/LucaUburti

@ShellyAmbar
Copy link

filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@OverRide
public void onComplete(@nonnull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
Toast.makeText(SettingActivity.this,"Your picture Saved successfully",Toast.LENGTH_SHORT) .show();
String DownloadUrl=task.getResult().getStorage().getDownloadUrl().toString();

@GenieCloud
Copy link

GenieCloud commented Dec 23, 2018

photoStorageReference.putFile(selectedImageUri).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task>() { @OverRide public Task then(@nonnull Task<UploadTask.TaskSnapshot> task) throws Exception { if (!task.isSuccessful()) { throw task.getException(); } return photoStorageReference.getDownloadUrl(); } }).addOnCompleteListener(new OnCompleteListener() { @OverRide public void onComplete(@nonnull Task task) { if (task.isSuccessful()) { Uri downloadUri = task.getResult(); FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUri.toString()); mMessagesDatabaseReference.push().setValue(friendlyMessage); } else { Toast.makeText(MainActivity.this, "upload failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show(); } } });

I have tried running this code and it finally got rid of the dreadful .getDownloadUrl error but the photo still will not store or display in the chat :'(

Did anyone else get their app to work?

@ShellyAmbar
Copy link

  //putting image into storage
            final StorageReference filePath= mStorageRef.child("Users_Profile_Picture").child(UserIdString+".jpg");
            filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                    if(task.isSuccessful()){
            //getting storage string

                      // String DownloadUrl= task.getResult().getDownloadUrl().toString();

                       // String DownloadUrl= task.getResult().getStorage().getDownloadUrl().toString();

                        filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {
                                String downloadUrl = uri.toString();

                                UserDataBase.child("Image").setValue(downloadUrl).addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        if(task.isSuccessful()){
                                            progressDialog.dismiss();
                                            Toast.makeText(SettingActivity.this,"Your picture Saved successfully",Toast.LENGTH_SHORT) .show();

                                        }else{
                                            Toast.makeText(SettingActivity.this,"Problem occurred while tryng to save your picture..",Toast.LENGTH_SHORT) .show();
                                        }
                                    }
                                });
                            }
                        });


            //uploading into database


                    }else{
                        Toast.makeText(SettingActivity.this,"Your picture did NOT saved",Toast.LENGTH_SHORT) .show();
                        progressDialog.dismiss();
                    }
                }
            });

Try this, works good !!!!!!! believe me... put this in the onActivityResult method...:)

@muhammadumerfarooq
Copy link

muhammadumerfarooq commented Dec 23, 2018

Try this code, it works for me

`

                final StorageReference ref = storageRef.child("mountains.jpg");

                UploadTask uploadTask = ref.putFile(imgUri);

                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();
                        }

                        // Continue with the task to get the download URL
                        return ref.getDownloadUrl();
                    }
                }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                    @Override
                    public void onComplete(@NonNull Task<Uri> task) {
                        if (task.isSuccessful()) {
                            Uri downloadUri = task.getResult();
                           // author.setText(downloadUri.toString());
                         //   Log.d("DownloadURL ",downloadUri.toString());
                        } else {
                            // Handle failures
                            // ...
                        }
                    }
                }).addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        //Uri downloadUri = task.getResult();
                        // author.setText(downloadUri.toString());
                          Log.d("DownloadURL ",uri.toString());
                    }
                });

`

@ChutiBro
Copy link

there has a same error, i can't understand how to fix that.please help

error

setupBtn.setOnClickListener( new View.OnClickListener() {
@OverRide
public void onClick(View v) {

            final String User_name=setupName.getText().toString();
            if (!TextUtils.isEmpty( User_name ) && mainImageURI!=null){

                User_ID=firebaseAuth.getCurrentUser().getUid();

                setup_Progress.setVisibility( View.VISIBLE );

                final StorageReference image_path=storageReference.child( "Profile_images" ).child( User_ID + ".jpg" );
                image_path.putFile( mainImageURI ).addOnCompleteListener( new OnCompleteListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {

                        if (task.isSuccessful()){

                            Uri  download_uri=task.getResult().getDownloadUrl();                                //StorageReference storageReference = FirebaseStorage.getInstance().getReference();


                            //Toast.makeText( SetupActivity.this,"The Image is Uploaded"+User_ID + ".jpg",Toast.LENGTH_LONG ).show();

                            Map<String, String> userMap=new HashMap<>();
                            userMap.put( "name",User_name);
                            userMap.put( "image",download_uri.toString());
                            //userMap.put( "image",User_ID+".jpg");


                            firebaseFirestore.collection( "Users" ).document(User_ID).set( userMap ).addOnCompleteListener( new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    if (task.isSuccessful()){
                                        Toast.makeText( SetupActivity.this,"User Settings are Updated !",Toast.LENGTH_LONG ).show();
                                        Intent MainIntent=new Intent( SetupActivity.this,MainActivity.class );
                                        startActivity( MainIntent );
                                        finish();
                                    }else {
                                        String error=task.getException().getMessage();
                                        Toast.makeText( SetupActivity.this,"FireStore Error : "+error,Toast.LENGTH_LONG ).show();
                                    }
                                    setup_Progress.setVisibility( View.INVISIBLE );
                                    setupBtn.setEnabled( true );
                                }
                            } );



                           }else {
                            String error=task.getException().getMessage();
                            Toast.makeText( SetupActivity.this,"Image Error : "+error,Toast.LENGTH_LONG ).show();
                            setup_Progress.setVisibility( View.INVISIBLE );
                            setupBtn.setEnabled( true );
                        }


                    }
                } );
            }
        }
    } );

@Parthav46
Copy link

@ChutiBro the error is due to getDownloadUrl() being deprecated.
Try using the solution given here

@ChutiBro
Copy link

@Parthav46 i tried
image
but can't find any suggest for Storage.

@Parthav46
Copy link

@ChutiBro try this

StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());

// Upload file to Firebase Storage
photoRef.putFile(selectedImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
        Task<Uri> uriTask = task.getResult().getStorage().getDownloadUrl();
        while(!uriTask.isComplete());
        Uri downloadUrl = uriTask.getResult();



        // Set the download URL to the message box, so that the user can send it to the database
        FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUrl.toString());
        mMessagesDatabaseReference.push().setValue(friendlyMessage);
     }
 });

@apereira2001
Copy link

apereira2001 commented Dec 30, 2018

Hey guys,

Try this code, it works for me:

package br.com.amptec.firebaseapp;

import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.io.ByteArrayOutputStream;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {

    private DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
    private FirebaseAuth auth = FirebaseAuth.getInstance();

    private Button btnUpload;
    private ImageView imgPhoto;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnUpload = findViewById(R.id.btnUpload);
        imgPhoto = findViewById(R.id.imgPhoto);

        btnUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                imgPhoto.setDrawingCacheEnabled(true);
                imgPhoto.buildDrawingCache();
                Bitmap bitmap = imgPhoto.getDrawingCache();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                byte[] imageBytes = baos.toByteArray();
                String fileName = UUID.randomUUID().toString();

                StorageReference storageReference = FirebaseStorage.getInstance().getReference();
                StorageReference images = storageReference.child("images");
                StorageReference imageRef = images.child(fileName + ".jpeg");

                UploadTask uploadTask = imageRef.putBytes(imageBytes);

                uploadTask.addOnFailureListener(MainActivity.this, new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(MainActivity.this, "Upload Error: " +
                                e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }).addOnSuccessListener(MainActivity.this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        //Uri url = taskSnapshot.getDownloadUrl();
                        Task<Uri> uri = taskSnapshot.getStorage().getDownloadUrl();
                        while(!uri.isComplete());
                        Uri url = uri.getResult();

                        Toast.makeText(MainActivity.this, "Upload Success, download URL " +
                                url.toString(), Toast.LENGTH_LONG).show();
                        Log.i("FBApp1 URL ", url.toString());
                    }
                });
            }
        });
    }
}

@GenieCloud
Copy link

@ChutiBro try this

StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());

// Upload file to Firebase Storage
photoRef.putFile(selectedImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
        Task<Uri> uriTask = task.getResult().getStorage().getDownloadUrl();
        while(!uriTask.isComplete());
        Uri downloadUrl = uriTask.getResult();



        // Set the download URL to the message box, so that the user can send it to the database
        FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUrl.toString());
        mMessagesDatabaseReference.push().setValue(friendlyMessage);
     }
 });

This solution works best! for getting the photos to upload and store in the database! :) The .getDownloadURL is no longer available and deprecated.

@DevPokhraj
Copy link

@ChutiBro try this

StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());

// Upload file to Firebase Storage
photoRef.putFile(selectedImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
        Task<Uri> uriTask = task.getResult().getStorage().getDownloadUrl();
        while(!uriTask.isComplete());
        Uri downloadUrl = uriTask.getResult();



        // Set the download URL to the message box, so that the user can send it to the database
        FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUrl.toString());
        mMessagesDatabaseReference.push().setValue(friendlyMessage);
     }
 });

How to get downloadUrl for Multiple files?

@aktarulahsan
Copy link

you can use that ....

String download_url= task.getResult().getUploadSessionUri().toString();

@sabiou
Copy link

sabiou commented Jan 23, 2019

This issue could be closed I think. 😄

@kevinkoech
Copy link

I faced the same problem but I got the answer

Just add .getStorage() infront of .getDownloadurl

to be like this below

.getStorage().getDownloadUrl 

LEAVE EVERYTHING IN THAT LINE DONT ALTER JUST ADD .getStorage()

@kickass23
Copy link

kickass23 commented Feb 9, 2019 via email

@kevinkoech
Copy link

welcome
one day also there is a problem about FirebaseRecyclerviewAdapter where they use FirebaseRecyclerOption bla bla which stresses too working on that

@mayokunadeniyi
Copy link

  //putting image into storage
            final StorageReference filePath= mStorageRef.child("Users_Profile_Picture").child(UserIdString+".jpg");
            filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                    if(task.isSuccessful()){
            //getting storage string

                      // String DownloadUrl= task.getResult().getDownloadUrl().toString();

                       // String DownloadUrl= task.getResult().getStorage().getDownloadUrl().toString();

                        filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {
                                String downloadUrl = uri.toString();

                                UserDataBase.child("Image").setValue(downloadUrl).addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        if(task.isSuccessful()){
                                            progressDialog.dismiss();
                                            Toast.makeText(SettingActivity.this,"Your picture Saved successfully",Toast.LENGTH_SHORT) .show();

                                        }else{
                                            Toast.makeText(SettingActivity.this,"Problem occurred while tryng to save your picture..",Toast.LENGTH_SHORT) .show();
                                        }
                                    }
                                });
                            }
                        });


            //uploading into database


                    }else{
                        Toast.makeText(SettingActivity.this,"Your picture did NOT saved",Toast.LENGTH_SHORT) .show();
                        progressDialog.dismiss();
                    }
                }
            });

Try this, works good !!!!!!! believe me... put this in the onActivityResult method...:)

This definitely worked!

@saggemode
Copy link

package com.saggemode;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FileDownloadTask;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;

import java.util.HashMap;

import de.hdodenhof.circleimageview.CircleImageView;

public class SettingsActivity extends AppCompatActivity {
private Button UpdateAccountSettings;
private EditText userName, userStatus;
private CircleImageView userProfileImage;

private String currentUserID;
private FirebaseAuth mAuth;
private DatabaseReference RootRef;

private static final int GalleryPick = 1;
private StorageReference UserProfileImagesRef;
private ProgressDialog loadingBar;

private Toolbar SettingsToolBar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);

    mAuth = FirebaseAuth.getInstance();
    currentUserID = mAuth.getCurrentUser().getUid();
    RootRef = FirebaseDatabase.getInstance().getReference();
    UserProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Profile Images");


    InitializeFields();


    userName.setVisibility(View.INVISIBLE);


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


    RetrieveUserInfo();


    userProfileImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent galleryIntent = new Intent();
            galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
            galleryIntent.setType("image/*");
            startActivityForResult(galleryIntent, GalleryPick);
        }
    });

}

private void InitializeFields() {
    UpdateAccountSettings = (Button) findViewById(R.id.update_settings_button);
    userName = (EditText) findViewById(R.id.set_user_name);
    userStatus = (EditText) findViewById(R.id.set_profile_status);
    userProfileImage = (CircleImageView) findViewById(R.id.set_profile_image);
    loadingBar = new ProgressDialog(this);

    SettingsToolBar = (Toolbar) findViewById(R.id.settings_toolbar);
    setSupportActionBar(SettingsToolBar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowCustomEnabled(true);
    getSupportActionBar().setTitle("Account Settings");
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == GalleryPick && resultCode == RESULT_OK && data != null) {
        Uri ImageUri = data.getData();

        CropImage.activity()
                .setGuidelines(CropImageView.Guidelines.ON)
                .setAspectRatio(1, 1)
                .start(this);
    }

    if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
        CropImage.ActivityResult result = CropImage.getActivityResult(data);

        if (resultCode == RESULT_OK) {
            loadingBar.setTitle("Set Profile Image");
            loadingBar.setMessage("Please wait, your profile image is updating...");
            loadingBar.setCanceledOnTouchOutside(false);
            loadingBar.show();

            Uri resultUri = result.getUri();


            final StorageReference filePath = UserProfileImagesRef.child(currentUserID + ".jpg");

            filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                    if (task.isSuccessful()) {
                        Toast.makeText(SettingsActivity.this, "Profile Image uploaded Successfully...", Toast.LENGTH_SHORT).show();

                        //final String downloadUrl = task.getDownloadUrl().toString();
                       // final String downloadUrl = task.getResult().getStorage().getDownloadUrl().toString();
                        //final String downloadUrl = task.getResult().getMetadata().getReference().getDownloadUrl().toString();

                        filePath.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
                            @Override
                            public void onComplete(@NonNull Task<Uri> task) {
                                final String downloadUrl = task.getResult().toString();

                                RootRef.child("Users").child(currentUserID).child("image")
                                        .setValue(downloadUrl)
                                        .addOnCompleteListener(new OnCompleteListener<Void>() {
                                            @Override
                                            public void onComplete(@NonNull Task<Void> task) {
                                                if (task.isSuccessful()) {
                                                    Toast.makeText(SettingsActivity.this, "Image save in Database, Successfully...", Toast.LENGTH_SHORT).show();
                                                    loadingBar.dismiss();
                                                } else {
                                                    String message = task.getException().toString();
                                                    Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
                                                    loadingBar.dismiss();
                                                }
                                            }
                                        });
                            }
                        });

                    } else {
                        String message = task.getException().toString();
                        Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    }
                }
            });
        }
    }
}

private void UpdateSettings() {
    String setUserName = userName.getText().toString();
    String setStatus = userStatus.getText().toString();

    if (TextUtils.isEmpty(setUserName)) {
        Toast.makeText(this, "Please write your user name first....", Toast.LENGTH_SHORT).show();
    }
    if (TextUtils.isEmpty(setStatus)) {
        Toast.makeText(this, "Please write your status....", Toast.LENGTH_SHORT).show();
    } else {
        HashMap<String, Object> profileMap = new HashMap<>();
        profileMap.put("uid", currentUserID);
        profileMap.put("name", setUserName);
        profileMap.put("status", setStatus);
        RootRef.child("Users").child(currentUserID).updateChildren(profileMap)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if (task.isSuccessful()) {
                            SendUserToMainActivity();
                            Toast.makeText(SettingsActivity.this, "Profile Updated Successfully...", Toast.LENGTH_SHORT).show();
                        } else {
                            String message = task.getException().toString();
                            Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
}

private void RetrieveUserInfo() {
    RootRef.child("Users").child(currentUserID)
            .addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("image")))) {
                        String retrieveUserName = dataSnapshot.child("name").getValue().toString();
                        String retrievesStatus = dataSnapshot.child("status").getValue().toString();
                        String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();

                        userName.setText(retrieveUserName);
                        userStatus.setText(retrievesStatus);
                        Picasso.get().load(retrieveProfileImage).placeholder(R.drawable.default_avatar).into(userProfileImage);
                    } else if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name"))) {
                        String retrieveUserName = dataSnapshot.child("name").getValue().toString();
                        String retrievesStatus = dataSnapshot.child("status").getValue().toString();

                        userName.setText(retrieveUserName);
                        userStatus.setText(retrievesStatus);
                    } else {
                        userName.setVisibility(View.VISIBLE);
                        Toast.makeText(SettingsActivity.this, "Please set & update your profile information...", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
}

private void SendUserToMainActivity() {
    Intent mainIntent = new Intent(SettingsActivity.this, MainActivity.class);
    mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(mainIntent);
    finish();
}

}

@ardakazanci
Copy link

ardakazanci commented Jul 10, 2019

My solution. The download address was "com.google.android.gms.tasks ...", so I couldn't use it with Glide. I've reviewed shared solutions. . I have reached this solution by following the path below.Maybe it's an inspiration. Thank's all. 🧸

mStorageRef.child("users").child(getUserInfo.userUID!!)
                    .child(profilePictureSelectedUri!!.lastPathSegment!!)
                    .putFile(profilePictureSelectedUri!!)
                    .addOnSuccessListener { itUploadTask ->
                        itUploadTask?.storage?.downloadUrl?.addOnSuccessListener { itUri ->
                            val downloadUrl: String = itUri.toString()
                            mDatabaseRef.child("users").child(getUserInfo.userUID!!)
                                .child("userDetails")
                                .child("userProfilePicture")
                                .setValue(downloadUrl).addOnCompleteListener { itTask ->
                                    if (itTask.isSuccessful) {
                                        //profileUpdateController = true -> it was necessary for me
                                        dialogPictureFragmentProgressFragment.dismiss()
                                        mStorageRef.downloadUrl
                                    } else {
                                        val message = itTask.exception?.message
                                        Toast.makeText(
                                            activity!!,
                                            "Error Occured..." + message,
                                            Toast.LENGTH_SHORT
                                        ).show()
                                    }
                                }
                        }
                    }

Helper : https://firebase.google.com/docs/storage/android/download-files#download_data_via_url

@Razalimustapa
Copy link

the getDownloadURL() is not inside the AngularFireUploadTask.. It is inside AngularFireStorageReference. Right click on the AngularFireStorageReference and click "Go to definition" you will find that method in there.

@kickass23
Copy link

kickass23 commented Jul 27, 2019 via email

@sa30coder
Copy link

sa30coder commented Sep 27, 2019

this code working in angular8

uploadfile(event:any){

const file:File=event.target.files[0]
console.log(file.name)

const metaData={'contenttype':file.type}
console.log(metaData)

const storageRef:firebase.storage.Reference =firebase.storage().ref('/photos')
const Uploadtask= storageRef.put(file)
console.log(file.name)

  storageRef.getDownloadURL().then((url)=>{firebase.database().ref('/photos').set(url)})

}

@nandafercer
Copy link

nandafercer commented Dec 6, 2019

Task urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();

I got it with this solution
Check my code:

else if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
            final Uri selectedImageUri = data.getData();
            //Toast.makeText(MainActivity.this, "Está no RC_PHOTO_picker! " + selectedImageUri.getLastPathSegment().toString(), Toast.LENGTH_SHORT).show();


            // Get a reference to store file at chat_photos/<FILENAME>
            StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());

            // Upload a file to Filebase Storage
            photoRef.putFile(selectedImageUri).addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
                    while (!urlTask.isSuccessful());
                        Uri downloadUrl = urlTask.getResult();

                    FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUrl.toString());
                    mMessagesDatabaseReference.push().setValue(friendlyMessage);
                }
            });
        }

@jonathanbcsouza
Copy link

Hey guys, is that issues still open?
@mfgabriel92 I remember I spent 3 days solving this, I think my gist will help you. 🙏

Before and after, you can compare both at glance.
https://gist.github.com/jonathanbcsouza/13929ab81077645f1033bf9ce45beaab

@noelvillaman
Copy link

taskSnapshot.uploadSessionUri.toString()

@prleubica
Copy link

thanks 1000 times Parthav46
I took your code and change it a litle bit and it works!!

private StorageReference userProfileImageRef;

userProfileImageRef = FirebaseStorage.getInstance().getReference().child( "Images" );

final StorageReference filePath = userProfileImageRef.child( userId + ".jpg" );
filePath.putFile( selectedImage )
.addOnSuccessListener( new OnSuccessListener<UploadTask.TaskSnapshot>() {
@OverRide
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful());
Uri downloadUrl = uriTask.getResult();
String dw = downloadUrl.toString();
Toast.makeText( ProfilActivity.this,dw,Toast.LENGTH_LONG ).show();
DocumentReference documentReference = fFirestore.collection("users").document(userId);
Map<String,Object> data = new HashMap<>();
data.put( "Slika",dw );
fFirestore.collection( "users" ).document(userId).set( data,SetOptions.merge() );

@Bhavya-22
Copy link

To get non null segment you need to use API 19 (KITKAT) and need to use NonNullException and asserts

Uri selectedImageUri = data.getData();

        // Get a reference to store file at chat_photos/<FILENAME>

        assert selectedImageUri != null;
        final StorageReference photoRef = mChatPhotosStorageReference.child(Objects.requireNonNull(selectedImageUri.getLastPathSegment()));

        // Upload file to Firebase Storage
        photoRef.putFile(selectedImageUri).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                if (!task.isSuccessful()) {
                    throw Objects.requireNonNull(task.getException());
                }
                return photoRef.getDownloadUrl();
            }
        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                if (task.isSuccessful()) {
                    Uri downloadUri = task.getResult();
                    assert downloadUri != null;
                    FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUri.toString());
                    mMessagesDatabaseReference.push().setValue(friendlyMessage);
                } else {
                    Toast.makeText(MainActivity.this, "upload failed: " + Objects.requireNonNull(task.getException()).getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });

@Anant99-sys
Copy link

Yes they deprecated and then removed that method.
I use the following code, similar to what is written in the docs.

photoStorageReference.putFile(selectedImageUri).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 photoStorageReference.getDownloadUrl();
    }
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
    @Override
    public void onComplete(@NonNull Task<Uri> task) {
        if (task.isSuccessful()) {
            Uri downloadUri = task.getResult();
            FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUri.toString());
            mMessagesDatabaseReference.push().setValue(friendlyMessage);
        } else {
            Toast.makeText(MainActivity.this, "upload failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
});

Yes they deprecated and then removed that method.
I use the following code, similar to what is written in the docs.

photoStorageReference.putFile(selectedImageUri).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 photoStorageReference.getDownloadUrl();
    }
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
    @Override
    public void onComplete(@NonNull Task<Uri> task) {
        if (task.isSuccessful()) {
            Uri downloadUri = task.getResult();
            FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUri.toString());
            mMessagesDatabaseReference.push().setValue(friendlyMessage);
        } else {
            Toast.makeText(MainActivity.this, "upload failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
});

fun upload(view: View){
val uuid=UUID.randomUUID()
val imageName="images/$uuid.jpg"
val storageReference =mStorageRef!!.child( imageName)
storageReference.putFile(selected!!).addOnSuccessListener { taskSnapshot ->
val downloadURL=mStorageRef!!.child(imageName).downloadUrl.toString()
println(downloadURL)
}.addOnFailureListener{exception ->
if (exception!= null){
Toast.makeText(applicationContext,exception.localizedMessage,Toast.LENGTH_LONG).show()
}
}.addOnCompleteListener{task ->
if (task.isComplete){
Toast.makeText(applicationContext,"Post Shared",Toast.LENGTH_LONG).show()
}
//intent
}
}

2020-04-28 15:03:57.552 4878-4878/com.example.firebaseinstagram E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.firebaseinstagram, PID: 4878
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:402)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397)
at android.view.View.performClick(View.java:6294) 
at android.view.View$PerformClick.run(View.java:24770) 
at android.os.Handler.handleCallback(Handler.java:790) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6494) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 
Caused by: kotlin.KotlinNullPointerException
at com.example.firebaseinstagram.UploadActivity.upload(UploadActivity.kt:48)
at java.lang.reflect.Method.invoke(Native Method) 
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397) 
at android.view.View.performClick(View.java:6294) 
at android.view.View$PerformClick.run(View.java:24770) 
at android.os.Handler.handleCallback(Handler.java:790) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6494) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 
2020-04-28 15:03:57.560 4878-4885/com.example.firebaseinstagram I/zygote: Do partial cod

Can you help in solving this

@jayesh-srivastava
Copy link

Just write this:-
Uri downloaduri=taskSnapshot.getStorage().getDownloadUrl().getResult();

@robertshort5511
Copy link

taskSnapshot.uploadSessionUri.toString()

this did the trick

@varun7952
Copy link

taskSnapshot.getStorage().getDownloadUrl().toString()

@DevRyz3n running this command would raise FileNotFoundException as the returned value is not the download url for file. Instead try this code where I have created a Task object to perform getDownloadUrl() task, waited for its completion in the main thread and then obtained the URL through getResult() function.

@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
     Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
     while (!urlTask.isSuccessful());
     Uri downloadUrl = urlTask.getResult();
     FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUrl.toString());
     mDatabaseReference.push().setValue(friendlyMessage);
}

Why if (task.isSuccessful()) not working but while (!urlTask.isSuccessful()); works? what's the logic behind while (!urlTask.isSuccessful()); can anyone please explain?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests