0

I get the value for the detectedLanguageCode variable inside the successListener, but out of the listener it becomes null. Why is that happening?

i have put my code in a thread but it doesnt seem to get working.

Thread thread = new Thread(new Runnable() {
            public void run() {
                FirebaseLanguageIdentification languageIdentifier =
                        FirebaseNaturalLanguage.getInstance().getLanguageIdentification();
                languageIdentifier.identifyLanguage(text)
                        .addOnSuccessListener(
                                new OnSuccessListener<String>() {
                                    @Override
                                    public void onSuccess(@Nullable String languageCode) {
                                        if (languageCode != "und") {
                                            detectedLanguageCode = languageCode;
                                            //At this point detectedLanguageCode gets value
                                        } else {
                                            Log.i(TAG, "Can't identify language.");
                                        }
                                    }
                                })

                        .addOnFailureListener(
                                new OnFailureListener() {
                                    @Override
                                    public void onFailure(@NonNull Exception e) {
                                        // Model couldn’t be loaded or other internal error.
                                        // ...
                                    }
                                });
            }
        });
        thread.start();

        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        //  At this point detectedLanguageCode is null.
ktsakiris
  • 59
  • 1
  • 10
  • because u're creating a new thread and you're trying to access it from another thread which is main :) – Zafer Celaloglu Sep 27 '19 at 17:32
  • 1
    Language identification happens on a separate thread, that you don't control. Any code that requires the result, should be inside the `OnSuccessListener`, or be called from there. If you want to make that reusable, you could use a custom callback interface, such as shown here (for the Firebase Database): https://stackoverflow.com/questions/50434836/getcontactsfromfirebase-method-return-an-empty-list/50435519#50435519 – Frank van Puffelen Sep 27 '19 at 20:01

0 Answers0