and-nd-firebase icon indicating copy to clipboard operation
and-nd-firebase copied to clipboard

UploadTask.TaskSnapshot doesn't have getDownloadUrl() method

Open mfgabriel92 opened this issue 7 years ago • 41 comments

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?

mfgabriel92 avatar May 29 '18 14:05 mfgabriel92

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

LucaUburti avatar May 31 '18 16:05 LucaUburti

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

developcodeza-matthew avatar Jun 12 '18 12:06 developcodeza-matthew

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

darkokoa avatar Jun 16 '18 14:06 darkokoa

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

Parthav46 avatar Jun 18 '18 17:06 Parthav46

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

}

}

kickass23 avatar Jun 19 '18 21:06 kickass23

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

sabiou avatar Jul 09 '18 18:07 sabiou

` 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.

achyutghosh avatar Aug 11 '18 05:08 achyutghosh

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

You should write resultCode

lantosgyuri avatar Aug 25 '18 16:08 lantosgyuri

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

kamrul4248hasan avatar Oct 24 '18 06:10 kamrul4248hasan

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

kamrul4248hasan avatar Oct 24 '18 06:10 kamrul4248hasan

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

ShellyAmbar avatar Dec 22 '18 20:12 ShellyAmbar

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

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?

GenieCloud avatar Dec 23 '18 00:12 GenieCloud

  //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...:)

ShellyAmbar avatar Dec 23 '18 02:12 ShellyAmbar

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

`

muhammadumerfarooq avatar Dec 23 '18 20:12 muhammadumerfarooq

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


                    }
                } );
            }
        }
    } );

ChutiBro avatar Dec 25 '18 10:12 ChutiBro

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

Parthav46 avatar Dec 26 '18 06:12 Parthav46

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

ChutiBro avatar Dec 26 '18 09:12 ChutiBro

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

Parthav46 avatar Dec 28 '18 06:12 Parthav46

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

apereira2001 avatar Dec 30 '18 02:12 apereira2001

@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.

GenieCloud avatar Dec 30 '18 05:12 GenieCloud

@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?

DevPokhraj avatar Jan 10 '19 04:01 DevPokhraj

you can use that ....

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

aktarulahsan avatar Jan 20 '19 15:01 aktarulahsan

This issue could be closed I think. :smile:

sabiou avatar Jan 23 '19 03:01 sabiou

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

kevinkoech avatar Feb 09 '19 12:02 kevinkoech

thank you it works fine now

On Sat, Feb 9, 2019 at 8:34 AM KEVIN koech [email protected] wrote:

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

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/udacity/and-nd-firebase/issues/41#issuecomment-462040844, or mute the thread https://github.com/notifications/unsubscribe-auth/AmiUaWdFDY-lerHYHxorFLL0a8cZwsmWks5vLsBhgaJpZM4URmLi .

kickass23 avatar Feb 09 '19 17:02 kickass23

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

kevinkoech avatar Feb 10 '19 16:02 kevinkoech

  //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!

mayokunadeniyi avatar May 25 '19 20:05 mayokunadeniyi

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

}

saggemode avatar Jun 30 '19 23:06 saggemode

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

ardakazanci avatar Jul 10 '19 18:07 ardakazanci

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.

Razalimustapa avatar Jul 18 '19 04:07 Razalimustapa