17

Before gradle update everything worked fine, but later on this error popped up. I have referred to the official documents and it provides the same code. Not accepting the getDownloadUrl() method

I have added the correct dependency which is latest and the gradle sync is successful. app/build.gradle

This is the sample code provided in firebase docs which is same as mine. Firebase Assistant

I'm unable to understand what could possibly go wrong even if all required things are present. Stuck on this since 2 days, please help!

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Karan
  • 370
  • 1
  • 3
  • 15

7 Answers7

15

As Doug pointed out, UploadTask.getDownloadUrl() is deprecated, so use StorageReference.getDownloadUrl().

But StorageReference.getDownloadUrl() returns Task, which must be handled asynchronously, you cannot do Uri downloadUrl = photoRef.getDownloadUrl().getResult(); else you will get java.lang.IllegalStateException: Task is not yet complete

Therefore, handle it asynchronously like this

 photoRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        Uri downloadUrl = uri;
                        Toast.makeText(getBaseContext(), "Upload success! URL - " + downloadUrl.toString() , Toast.LENGTH_SHORT).show();
                    }
                });
Ananth
  • 2,597
  • 1
  • 29
  • 39
10

If you have a 'image_uri' and put it to the firebase storage this code will help you.

private StorageReference storageReference= FirebaseStorage.getInstance().getReference();

 final StorageReference ref = storageReference.child("picture.jpg");
    ref.putFile(image_uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override
                public void onSuccess(Uri uri) {
                    final Uri downloadUrl = uri;


                }
            });
Thamarai Selvan
  • 131
  • 1
  • 6
  • 1
    no longer provides 'getDownloadUrl' method, that is the reason the problem occured. Instead I did as specified here https://firebase.google.com/docs/storage/android/upload-files?authuser=0 – Karan Jun 08 '18 at 13:14
  • This answer is wrong. The [`StorageReference.getDownloadUrl()`](https://firebase.google.com/docs/reference/android/com/google/firebase/storage/StorageReference.html#getDownloadUrl()) method returns a `Task`. So `ref.getDownloadUrl().toString()` call just gives you a string representation of the `Task`, not the actual URL. This answer shows the correct way: https://stackoverflow.com/a/51076403 – Frank van Puffelen Jul 05 '18 at 19:22
  • 1
    I just edited the above code. please check .That will work now.@FrankvanPuffelen – Thamarai Selvan Jul 06 '18 at 20:11
6

getDownloadUrl no longer exists.

So the new method is:

final StorageReference ref = storageRef.child("images/mountains.jpg");
uploadTask = ref.putFile(file);

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();
        } else {
            // Handle failures
            // ...
        }
    }
});

Firebase doc

Pablo Cegarra
  • 20,955
  • 12
  • 92
  • 110
5

UploadTask.getDownloadUrl() is deprecated. Use StorageReference.getDownloadUrl() instead.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • 2
    Deprecation of this is true, but using those in older versions of applications never caused a problem, app never crashed! Considering a deprecation example, developers still use "ProgressDialog", even though it is deprecated it is still functional. That was my point! – Karan Jun 08 '18 at 13:12
  • storageReference.getDownloadUrl() working fine with '16.0.5' – Sandeep Feb 02 '19 at 15:39
2

For kotlin

val uploadTask = fileReference.putFile(Uri.fromFile(primaryFile), metadata)

and

        uploadTask
                .addOnProgressListener { taskSnapshot ->

                }

                .addOnPausedListener { 

                }

                .addOnSuccessListener { taskSnapshot ->
                }
                .continueWithTask { task ->
                    if (!task.isSuccessful) {
                        throw task.exception!!
                    }
                 fileReference.downloadUrl
                }

                .addOnCompleteListener { task ->

                    if (task.isSuccessful) {
                        val downloadUrl: Uri = task.result

                    } else {
                        // Handle failures
                    }
                }

                .addOnFailureListener { e ->

                }

val downloadUrl is your URL that is uploaded.

Kishan Solanki
  • 13,761
  • 4
  • 85
  • 82
0
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
    filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
        @Override
        public void onSuccess(Uri uri) {
            Map newImage = new HashMap();
            newImage.put("profileImageUrl", uri.toString());
            mDriverDatabase.updateChildren(newImage);

            finish();
            return;
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            finish();
            return;
        }
    });
}

}); **we can use get download url in this way because firebase do some changes **

0

Try this code..

public class MainActivity extends AppCompatActivity {

String LOG_TAG = MainActivity.class.getSimpleName();

Button buttonUpload, buttonDownload;
RadioGroup radioGroup;
ImageView imageviewResult;

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

    buttonUpload = findViewById(R.id.upload_button);
    buttonDownload = findViewById(R.id.download_button);
    radioGroup = findViewById(R.id.radio_group);
    imageviewResult = findViewById(R.id.resultant_imageview);

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

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

private void uploadImage() {
    // Start by getting our StorageReference
    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference rootRef = storage.getReference();
    StorageReference bearRef = rootRef.child("images/bear.jpg");
    final ProgressDialog progressDialog = new ProgressDialog(this);
    progressDialog.setTitle("Uploading");
    progressDialog.show();

    // Get the data from the image as bytes
    ImageView bearImage = getSelectedBearImage();
    bearImage.setDrawingCacheEnabled(true);
    bearImage.buildDrawingCache();
    Bitmap bitmap = bearImage.getDrawingCache();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] data = baos.toByteArray();

    // Upload it to our reference
    UploadTask uploadTask = bearRef.putBytes(data);
    buttonDownload.setEnabled(false);
    uploadTask.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            // Handle unsuccessful uploads
            progressDialog.dismiss();

            Log.w(LOG_TAG, "Upload failed: " + exception.getMessage());
        }
    }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
            Uri downloadUrl = taskSnapshot.getDownloadUrl();
            progressDialog.dismiss();

            Log.d(LOG_TAG, "Download Url: " + downloadUrl);
            buttonDownload.setEnabled(true);
        }
    });
}

private void downloadImage() {
    // Start by getting a reference to the same location we uploaded to
    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference rootRef = storage.getReference();
    StorageReference bearRef = rootRef.child("images/bear.jpg");
    final ProgressDialog progressDialog = new ProgressDialog(this);
    progressDialog.setTitle("Uploading");
    progressDialog.show();

    // Download our data with a max allocation of 1MB
    final long ONE_MEGABYTE = 1024 * 1024;
    bearRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
        @Override
        public void onSuccess(byte[] bytes) {
            // Convert bytes to bitmap and call setImageBitmap
            progressDialog.dismiss();
            Log.d(LOG_TAG, "Download successful");
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            imageviewResult.setImageBitmap(bitmap);
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            // Handle any errors
            progressDialog.dismiss();

            Log.w(LOG_TAG, "Download failed: " + exception.getMessage());
        }
    });
}

private ImageView getSelectedBearImage() {
    switch (radioGroup.getCheckedRadioButtonId()) {
        case R.id.radio1:
            return findViewById(R.id.image_bear1);
        case R.id.radio2:
            return findViewById(R.id.image_bear2);
        case R.id.radio3:
            return findViewById(R.id.image_bear3);
        case R.id.radio4:
            return findViewById(R.id.image_bear4);
        default:
            return findViewById(R.id.image_bear1);
    }
}

}

activity.xml..

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.adruser.firebasestorageapp.MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="96dp"
    android:orientation="horizontal">
    <ImageView
        android:id="@+id/image_bear1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:scaleType="centerInside"
        android:src="@drawable/a"/>
    <ImageView
        android:id="@+id/image_bear2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:scaleType="centerInside"
        android:src="@drawable/tiger"/>
    <ImageView
        android:layout_width="0dp"
        android:id="@+id/image_bear3"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:scaleType="centerInside"
        android:src="@drawable/download"/>
    <ImageView
        android:layout_width="0dp"
        android:id="@+id/image_bear4"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:scaleType="centerInside"
        android:src="@drawable/add"/>
</LinearLayout>

<RadioGroup
    android:id="@+id/radio_group"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <RadioButton
        android:id="@+id/radio1"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:checked="true"
        android:layout_height="wrap_content" />
    <RadioButton
        android:id="@+id/radio2"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />
    <RadioButton
        android:id="@+id/radio3"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />
    <RadioButton
        android:id="@+id/radio4"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content" />
</RadioGroup>

<TextView
    android:layout_marginTop="16dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Downloaded Image"/>

<ImageView
    android:id="@+id/resultant_imageview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"/>

<Button
    android:id="@+id/upload_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="24dp"
    android:text="Upload"/>

<Button
    android:id="@+id/download_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:enabled="false"
    android:layout_marginTop="8dp"
    android:text="Download"/>

</LinearLayout>

and i hope you connetcted with firebase storage and give internet permission..

    <uses-permission android:name="android.permission.INTERNET"/>

more information refer this link.. https://code.tutsplus.com/tutorials/image-upload-to-firebase-in-android-application--cms-29934