0

I am currently experimenting with ML Kit and the local Firebase framework for detecting and analysing faces.
I have a gallery activity where the user can choose an image and is directed to another activity where the selected image is displayed and the faces are analysed (I boiled the code down so that the problem is more clear):

private void classifyFaces(final Bitmap bitmap){

    FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);


    Task<List<FirebaseVisionFace>> result =
            detector.detectInImage(image)
                    .addOnSuccessListener(
                            new OnSuccessListener<List<FirebaseVisionFace>>() {
                                @Override
                                public void onSuccess(List<FirebaseVisionFace> faces) {
                                    // Task completed successfully

                                    // Do face analysis tasks here.
                            })
                    .addOnFailureListener(
                            new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception e) {
                                    // Task failed with an exception
                                    // ...
                                }
                            });
}

This code works fine if it is located in the respective activity class. I then rewrote the classifyFaces method to return the result of the analysis and moved it into a separate package. Then I called the newly created class from my activity and never got a return value.

I think it has something to do with how the Firebase task works and that the classifyFaces method returns before the OnSuccessListener is fired.
I tried different methods like passing the DisplayImage activity to the addOnSuccessListener method but it didn't work.

How can I fix this?

bennyOoO
  • 358
  • 2
  • 11

1 Answers1

1

The reason is that the Task is running asynchron. So your method just starts the Task and returns before it has already finished.

Maybe you can make your method return a Task. Then you can register onCompleteListener in the calling activity.

Thomas Meinhart
  • 659
  • 2
  • 7
  • 28