0

I have an ArrayList of strings that I use to store image URLs. Inside a for loop, I add a value to the ArrayList each time but after the for loop, the ArrayList seems to reset itself.

for (int i = 0; i < imageUris.size(); i++) {
    imageFilePath = storageReference.child(imageUris.get(i).getLastPathSegment());

    StorageReference finalImageFilePath = imageFilePath;
    imageFilePath.putFile(imageUris.get(i)).addOnSuccessListener(taskSnapshot -> {
        finalImageFilePath.getDownloadUrl().addOnSuccessListener(uri -> {

            String imageUrl = uri.toString();
            imageUrls.add(imageUrl); // Here I'm adding to the ArrayList

            Log.d("test1", String.valueOf(imageUrls.size())); // the size is 1

        });
}


Log.d("test2", String.valueOf(imageUrls.size())); // the size is 0

EDIT:

I can't answer my own question so here is the solution (can see in comments): the problem here is that I update the list in an addOnSuccessListener, since this function works on another thread, the code keeps running, therefor it prints the list in it's first form (before adding urls to it).

Ido Barnea
  • 142
  • 2
  • 13

2 Answers2

0

Make sure your imageUrls variable instance variable not a local variable. If it is a local variable then keep it outside the specific method.

Priyanka
  • 1,791
  • 1
  • 7
  • 12
0

maybe you put this array as local so before oncrate put this code ArrayList<String> imageUrls=new ArrayList<>(); now the variable is global and if you want ArrayList is saved until the application is closed just make array static

Mohsen El Sayed
  • 135
  • 3
  • 11