Mohammad Maaz
Mohammad Maaz

Reputation: 137

Can someone help me with logic of the firebase on success listener

I am adding and retrieving images from firebase database. When an image is uploaded, it is displayed on another activity in recyclerview. When adding multiple images, then activity keeps opening in the loop i.e dependent on how many images are added. I want to open all activities at once when all images are successfully added. I tried making a logic in which an int a is compared with the mClipData.getItemCount() but it doesn't give any solution kindly help me with this problem

P.S: the code given is for multiple images

    if (data.getClipData() != null) {
        ClipData mClipData = data.getClipData();
        ArrayList<Uri> mArrayUri = new ArrayList<>();
        for (int i = 0; i < mClipData.getItemCount(); i++) {

            final ClipData.Item item = mClipData.getItemAt(i);
            final Uri mImageUri = item.getUri();
            mArrayUri.add(mImageUri);
            // Get the cursor
            Cursor cursor = getContentResolver().query(mImageUri, filePathColumn, null, null, null);
            // Move to first row
            cursor.moveToFirst();

            final StorageReference profileStorage = uploadStorage.child(mImageUri.getLastPathSegment());
            uploadTask = profileStorage.putFile(mImageUri);
            final int finalI = i;
            uploadTask.addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    showMessage(e.toString());
                }
            }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    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();
                            }
                            downloadURL = profileStorage.getDownloadUrl().toString();
                            return profileStorage.getDownloadUrl();
                        }
                    }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                        @Override
                        public void onComplete(@NonNull Task<Uri> task) {
                            if(task.isSuccessful()){
                                Uri uri = task.getResult();
                                idRef.child(mImageUri.getLastPathSegment()).setValue(uri.toString());
                            }
                        }
                    }).addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {
                            showMessage("image upload successful ");
                            // activity opens multiple times check it //
                            a++;
                        }
                    });
                }
            });

            if(a == mClipData.getItemCount()){
                Intent intent = new Intent(getApplicationContext(), DisplayImages.class);
                startActivity(intent);
            }

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            imageEncoded  = cursor.getString(columnIndex);
            imagesEncodedList.add(imageEncoded);
            cursor.close();
        }

    }

Upvotes: 1

Views: 240

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598765

When you upload the images, the following sequence happens for each:

  1. You start the upload.
  2. Once that completes, you determine the download URL for the image.
  3. Once that completes, you write the download URL to the database.

Each of these operations is asynchronous, which you handle via tasks. Since you want the popup to only be shown once all download URLs are written to the database, the code should be in the last completion handler:

}).addOnSuccessListener(new OnSuccessListener<Uri>() {
    @Override
    public void onSuccess(Uri uri) {
        showMessage("image upload successful ");
        // activity opens multiple times check it //
        a++;

        if(a == mClipData.getItemCount()){
            Intent intent = new Intent(getApplicationContext(), DisplayImages.class);
            startActivity(intent);
        }
    }
});

Upvotes: 3

Related Questions