1

In the following code I write the result of a procedure into a Text field. The code is executed as part of a task.

I want "transfer" text (String "test") to onSuccess() method, so that I can use it within onSuccess(). I do not want to do that via static / global variables.

My question is: can I transfer data to the onSucess() method?

private void recognizeTextFromImage(InputImage image) {
 String test = "Test"
 TextRecognizer recognizer = TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS);
 Task<Text> task = recognizer.process(image);
 // recognizer.process(image)
 task
 .addOnSuccessListener(
 new OnSuccessListener<Text>() {
 @Override
 public void onSuccess(Text texts) {
 recognizedText = processTextRecognitionResult(texts);
 editText_Test.setText(test + recognizedText);
 Log.d(TAG,"Successful: " + recognizedText);
 }
 })
 .addOnFailureListener(
 new OnFailureListener() {
 }
 });
 recognizer.close();
}
asked Oct 25, 2021 at 17:43
4
  • Did you actually run the code you pasted? You can just use test in there. It'll work fine. Commented Oct 25, 2021 at 18:45
  • Yes :-) But variable "test" is some kind of "global". If another caller starts the method, the data will be overwritten and the "old" thread would get the wrong data. I need this data and variable "locally". Commented Oct 25, 2021 at 19:01
  • Right before task.addOnSuccessListener(..., write: String myTest = test; and then use myTest. Commented Oct 25, 2021 at 20:04
  • @rzwitserloot, thank you. Is there a difference to my code? Maybe I did not understand you correctly. Commented Oct 26, 2021 at 8:32

1 Answer 1

1

Variable "test" is not some kind of "global". It is a local variable by definition, and as such, a new one will be instantiated every time a caller starts the method. I can see no concurrency issue with just using the test variable within onSuccess, unless TextRecognizer is implemented in some really weird way.

answered Oct 25, 2021 at 20:50
Sign up to request clarification or add additional context in comments.

1 Comment

Yes. Thank you. My fault. It works now as expected.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.