0

I am trying to upload a photo in my database, the upload is working fine, but I need to get the url.

I can't get image url from Firebase using .getDownloadUrl(), in my database I have this "com.google.android.gms.tasks.zzu@e2b2b97" instead of the link.

Here is my code. Please help me, I am a beginner.

package com.mecachrome.ffbf;

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

import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;

public class addrestaurant extends AppCompatActivity {

private ImageView upload_image;
private EditText restaurant_name;
private EditText restaurant_add;
private EditText restaurant_desc;
private Button upload_button;
private ProgressBar progressBar;

private Uri restaurantImgUri;

private StorageReference storageref;
private DatabaseReference databaseref;

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

    upload_image = findViewById(R.id.iv_upload);
    restaurant_name = findViewById(R.id.text_restaurant_name);
    restaurant_add = findViewById(R.id.text_restaurant_address);
    restaurant_desc = findViewById(R.id.text_restaurant_description);
    upload_button = findViewById(R.id.upload_btn);
    progressBar = findViewById(R.id.progressBar);
    String url;

    storageref = FirebaseStorage.getInstance().getReference("restaurants");
    databaseref = FirebaseDatabase.getInstance().getReference("restaurants");
    
    upload_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            submit_restaurant();
        }

    });

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

        private void uploadImage() {
            Intent uploadImg = new Intent();
            uploadImg.setType("image/*");
            uploadImg.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(uploadImg,2);
        }
    });

}

private String getFileExtension(Uri uri) {
    ContentResolver cR = getContentResolver();
    MimeTypeMap mime = MimeTypeMap.getSingleton();
    return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void submit_restaurant() {
    if(restaurantImgUri !=null){
        StorageReference fileReference = storageref.child(System.currentTimeMillis() + "." + getFileExtension(restaurantImgUri));

        fileReference.putFile(restaurantImgUri)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                progressBar.setProgress(0);
                            }
                        },3000);
                        progressBar.setVisibility(View.INVISIBLE);
                        String url = databaseref.push().getKey();
                        Toast.makeText(addrestaurant.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
                        places restaurant = new places(restaurant_name.getText().toString().trim(),restaurant_desc.getText().toString().trim(),
                                taskSnapshot.getMetadata().getReference().getDownloadUrl().toString(),5, restaurant_add.getText().toString().trim());
                        String uploadId = databaseref.push().getKey();
                        databaseref.child(uploadId).setValue(restaurant);

                    }
                }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(addrestaurant.this, e.toString(), Toast.LENGTH_SHORT).show();
            }
        }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onProgress(@NonNull UploadTask.TaskSnapshot snapshot) {
                double progress = (100.0 * snapshot.getBytesTransferred()/ snapshot.getTotalByteCount());
                progressBar.setVisibility(View.VISIBLE);
                progressBar.setProgress((int) progress);

            }
        });
    }else{
        Toast.makeText(this, "No file selected!", Toast.LENGTH_SHORT).show();
    }
}

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

    if (requestCode == 2 && resultCode == RESULT_OK
            && data !=null && data.getData() != null){
        restaurantImgUri = data.getData();

        Picasso.get().load(restaurantImgUri).into(upload_image);
    }
}

}

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • This is **not** how to get the download URL: `taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()` Determining the download URL requires a call to the server. Because of this, the call to `getDownloadUrl()` returns a `Task` that completes when the download URL comes back from the server. You'll need to call `addSuccessListener()` on it to wait for it to complete. See the documentation [here](https://firebase.google.com/docs/storage/android/download-files#download_data_via_url) and this [answer](https://stackoverflow.com/a/51064689) – Frank van Puffelen Nov 24 '21 at 21:47
  • Can you please help me where do I need to use addSuccessListener()? – Zabava Mihai Nov 24 '21 at 22:50
  • Right after the call to `.getDownloadUrl()`, just as I have in the answer I linked. – Frank van Puffelen Nov 24 '21 at 22:54
  • I know I might be annoying, but I am very confused. Can you please give me a hand. what I need is to upload an image in my firebase storage and to use that image to show it in a image view. What do you suggest me to do, to use "places" constructor after the image is uploaded will be a good idea? Where should I write the code for the places object to be saved, after the image is uploaded? Because I tried to the addSuccessListener() after getDownloadUrl, but it doesn't work, i know the url is int "uri" but how do i get it out from there and put in in my "places" object? – Zabava Mihai Nov 24 '21 at 23:04
  • You need to call `getDownloadUrl().addOnSuccessListener()` as shown in the documentation and answer I linked. The `com.google.android.gms.tasks.zzu@e2b2b97` you get comes from doing `taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()` in your code. – Frank van Puffelen Nov 24 '21 at 23:56

0 Answers0