0

I am trying to get list of all Url from Firebase Storage into ArrayList. I tried using getDownloadUrl() method but ArrayList remains empty.

Here is my code-


public class LoggedIn extends AppCompatActivity {
RecyclerView recyclerView;
    
    ArrayList<Uri> Url=new ArrayList<>();
StorageReference storageReference= FirebaseStorage.getInstance().getReference();
    int in;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_logged_in);
        Bundle extras=getIntent().getExtras();
        String value = extras.getString("email");

        for(in=1;in<6;in++){
            storageReference.child(in+".png").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override
                public void onSuccess(Uri uri) {

                    Url.add(in,uri);
                    Log.d("success",String.valueOf(uri));

                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.d("Failed",String.valueOf(e));
                }
            });


        }
}}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

2

My guess is that you're using the Url list before Url.add(in,uri) has executed.

Since getDownloadUrl() requires a call to the server, it is handled asynchronously. This means that your main code continues to run, while the app waits for the download URL in the background. Then once the download URL is available, your onSuccess is called with that value.

I'll link some similar problems below, but the important thing to remember is that any code that needs the download URL, needs to be inside the onSuccess or be called from there.

If you want to wait for all download URLs to be available, you can use Tasks.whenAllSuccess.

Task[] tasks = new Task[6];
for(in=1;in<6;in++){
    Task task = storageReference.child(in+".png").getDownloadUrl();
    tasks[i] = task;
    task.addOnSuccessListener(new OnSuccessListener<Uri>() {
        @Override
        public void onSuccess(Uri uri) {
            Url.add(in,uri);
            Log.d("success",String.valueOf(uri));
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.d("Failed",String.valueOf(e));
        }
    });
}
Tasks.whenAllSuccess(tasks).addOnSuccessListener(new OnSuccessListener<List<Uri>>() {
    @Override
    public void onSuccess(List<Uri> results) {
        ... you can use `resuls` or `Url` here
    }
})

See also:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807