Search code examples
javaandroidfirebase-mlkit

variable return null after method finished


im trying to make a function that translate a text and print the result. im using firebasetranslator.

by debugging, the app starts but the textbox is empty. trying to put a marker on

private void setRisultato(String string){
            this.risultato = string;
}

I see that the translated text is correctly assigned to the result variable. but if I put the marker up

public String getRisultato(){
    return risultato;
}

I see what result is null (not empty), can someone explain me why?

UPDATE:

Traduttore.java

import android.app.Activity;
import androidx.annotation.NonNull;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.ml.common.modeldownload.FirebaseModelDownloadConditions;
import com.google.firebase.ml.naturallanguage.FirebaseNaturalLanguage;
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslateLanguage;
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslator;
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslatorOptions;


public class Traduttore extends Activity {
    private static String text1;

    public interface callbacktranslate {
        void onCallback(String risultato);
    }
    public void traduci(String textblock, final callbacktranslate callback){
        //clear string and start translate
        String blocktext = textblock.replaceAll("\n"," ");
        String blocktext2 = blocktext.replaceAll("\\.","");
        String blocktext3 = blocktext2.toUpperCase();
        text1 = blocktext3;
        downloadTranslatorAndTranslate(callback);
    }
    public void translateText(FirebaseTranslator langTranslator, final callbacktranslate callback) {
        //translate source text to english
        langTranslator.translate(text1).addOnSuccessListener(
                        new OnSuccessListener<String>() {
                            @Override
                            public void onSuccess(@NonNull String translatedText) {
                                //make variable all uppercase and save it
                                String blocktext4 = translatedText.toUpperCase();
                                callback.onCallback(blocktext4);
                            }
                        })
                .addOnFailureListener(
                        new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                            }
                        });
    }
    public void downloadTranslatorAndTranslate(final callbacktranslate callback) {
        int sourceLanguage = 11; //language source(en=11)
        //create translator for source and target languages
        FirebaseTranslatorOptions options =
                new FirebaseTranslatorOptions.Builder()
                        .setSourceLanguage(sourceLanguage)
                        .setTargetLanguage(FirebaseTranslateLanguage.IT)
                        .build();
        final FirebaseTranslator langTranslator =
                FirebaseNaturalLanguage.getInstance().getTranslator(options);
        //download language models if needed
        FirebaseModelDownloadConditions conditions = new FirebaseModelDownloadConditions.Builder()
                .build();
        langTranslator.downloadModelIfNeeded(conditions)
                .addOnSuccessListener(
                        new OnSuccessListener<Void>() {
                            @Override
                            public void onSuccess(Void v) {
                                translateText(langTranslator,callback);
                            }
                        })
                .addOnFailureListener(
                        new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                            }
                        });
    }
}

method in MainActivity.java:

public ConstraintLayout vpp;
public TextView[] textViewArray = new TextView[500];
public int i;

public void StartReadImage(){
    FirebaseVisionImage image2 = FirebaseVisionImage.fromBitmap(resizedBitmap);
    FirebaseVisionTextRecognizer textRecognizer2 = FirebaseVision.getInstance()
            .getOnDeviceTextRecognizer();
    final Task<FirebaseVisionText> result2 =
            textRecognizer2.processImage(image2)
                    .addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
                        @Override
                        public void onSuccess(FirebaseVisionText firebaseVisionText) {
                            // Task completed successfully
                           i = 0;
                            resultText = firebaseVisionText.getText();

                            for (FirebaseVisionText.TextBlock block: firebaseVisionText.getTextBlocks()) {
                                String blockText = block.getText();
                                Float blockConfidence = block.getConfidence();
                                List<RecognizedLanguage> blockLanguages = block.getRecognizedLanguages();

                                final  Point[] blockCornerPoints = block.getCornerPoints();
                                final  Rect blockFrame = block.getBoundingBox();

                                traduttore.traduci(blockText, new Traduttore.callbacktranslate() {
                                    @Override
                                    public void onCallback(String result) {
                                        createCover(blockCornerPoints, blockFrame, result, i);
                                        i++;
                                    }
                                });
                            }
                        }
                    })
                    .addOnFailureListener(
                            new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception e) {
                                    // Task failed with an exception
                                }
                            });
}
public void createCover(Point[] CornerPoint,Rect blockFrame,String blockText, int i){

            textViewArray[i] = new TextView(context);
            textViewArray[i].setTextSize(9);
            textViewArray[i].setGravity(Gravity.CENTER);
            textViewArray[i].setTextColor(Color.BLACK);
            textViewArray[i].setBackgroundColor(Color.rgb(225, 225, 225));
            textViewArray[i].setHeight(blockFrame.height());
            textViewArray[i].setWidth(blockFrame.width());
            textViewArray[i].setX(CornerPoint[0].x);
            textViewArray[i].setY(CornerPoint[0].y);

            textViewArray[i].setText(blockText);
            vpp.addView(textViewArray[i]);
}

Solution

  • You'll need to set the callback somewhere, and in order to do that, you'll need to add it a few places, and pass it on appropriately

    traduci(String textblock, final Callback callback)
    
    downloadTranslatorAndTranslate(final Callback callback)
    
    translateText(FirebaseTranslator langTranslator, final Callback callback)
    

    From there, you need to add the callback to the Activity method call, and that method should be void since the callback comes later from when the method actually returns

    public void Traduciblocco(String abc){
        traduttore.traduci(abc, new Callback() {
            @Override 
            public void onCallback(String result) {
                // resultTxt.setText(result); 
            } 
        });
    }