may have stopped the asynchronous behavior of firebase storage

Viewed 43

I use the firebase storage service to recover image batches I have named as follows:

  • 1a - for the first page of the image
  • 1b - for the second page of the image
  • 1c - for the third page of the image
  • 1d - for the fourth page of the image
  • 1e - for the fifth page of the image
  • 1f - for the sixth page of the image
  • 1g - for the seventh page of the image

I named them so that I could go through the party’s letters from A to Z and upload one by one the images;

as in the code extract below:

public void recuperationDansGridView2()  {

    for (char lettre = 'a'; lettre <= 'z'; lettre++) {

        String parcourDeslimage = "1"+lettre;

        // declarer une instance pour le stockage
        FirebaseStorage storage = FirebaseStorage.getInstance();
        // Create a storage reference from our app
        StorageReference storageRef= storage.getReference("sujet_simple/"+nonDeLImageIci+"/"+parcourDeslimage.trim()+".jpg");

        try {

            //cree un fichier temporaire qui stockera l'image en question
            File localFile = File.createTempFile("images", "jpg");
            storageRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {

                    // recupere limage contenue dans se fichier locale dans le bitmap
                    Bitmap bitmapConvertisseur = BitmapFactory.decodeFile(localFile.getAbsolutePath());
                    arrayBitmap.add(bitmapConvertisseur);

                    //daptateurGridView
                    gridView_listeDesSujets.setAdapter(new adaptateurGridView(ctx,arrayBitmap));
                    Toast.makeText(ctx, " appel de l'adaptateur ",Toast.LENGTH_LONG).show();

                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    
                }
            });
        }
        catch (IOException e) {

        }
    }

}

but I would like to stop downloading and exit the for loop if an image is missing:

I explain exp: if the image 1e is missing is that everything else that follows (1f , 1g ,etc.) is obviously missing therefore the download must be stopped and out of the loop to avoid an ANR (Application not responding )

but firebase downloads these images asynchronously which causes me problem for stop the download and exit of the loop it loops indefinitely up to 1z even if the images are missing .

because it can start downloads with 1f image first rather than start in order by image 1a and so on .

so my loop never stops how to stop it? or can’t have stopped this asynchronous behavior or if you have Other solution I follow taking.

1 Answers

You can use a workaround if you want. Assuming that you are using your app to upload/delete images, you can maintain a document in Firestore to keep count of these images. This way, you can check how many images are there using a single call.

DocumentReference docRef = db.collection("your_collection").document("image_counter");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {
                Map map = document.data;
                String counter = map.get("counter"); //assuming it is stored like counter:"f" 
                recuperationDansGridView2(counter);
            } else {
                Log.d(TAG, "No such document");
            }
        } else {
            Log.d(TAG, "get failed with ", task.getException());
        }
    }
});

You'll have to update the function as following :


public void recuperationDansGridView2(String counter)  {

    for (char lettre = 'a'; lettre <= counter.charAt(0); lettre++) {

        String parcourDeslimage = "1"+lettre;

        // declarer une instance pour le stockage
        FirebaseStorage storage = FirebaseStorage.getInstance();
        // Create a storage reference from our app
        StorageReference storageRef= storage.getReference("sujet_simple/"+nonDeLImageIci+"/"+parcourDeslimage.trim()+".jpg");

        try {

            //cree un fichier temporaire qui stockera l'image en question
            File localFile = File.createTempFile("images", "jpg");
            storageRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {

                    // recupere limage contenue dans se fichier locale dans le bitmap
                    Bitmap bitmapConvertisseur = BitmapFactory.decodeFile(localFile.getAbsolutePath());
                    arrayBitmap.add(bitmapConvertisseur);

                    //daptateurGridView
                    gridView_listeDesSujets.setAdapter(new adaptateurGridView(ctx,arrayBitmap));
                    Toast.makeText(ctx, " appel de l'adaptateur ",Toast.LENGTH_LONG).show();

                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    
                }
            });
        }
        catch (IOException e) {

        }
    }

}

Also don't forget to update the this document whenever you add or delete a file. You can do it like this:

DocumentReference docRef = db.collection("your_collection").document("image_counter");
Map map<String,String> = new HashMap<>();
map.put("counter","z");
docRef.set(map);
Related