0

I am new to Java and and not sure how to do this correctly.

I have a String variable textMain and I would like to pass it into a new object TextToSpeech. Is it possible? If so, how to do it?

I have to declare this variable outside of the object, unfortunately this object does not 'see' this variable.

String textMain = "text text";
textToSpeechSystem = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            speak(textMain); // textMain doesn't visible
        }
    }
});

Sorry if I wrote something wrong, I don't know the correct nomenclature yet.

Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35

3 Answers3

1

Your object you want to pass the string needs to have a field to store the value

Let's say that you have a class TextToSpeech with a constructor that has a string parameter to set the value at object creation.

public class TextToSpeech {
  private String textMain;
  ...

  public TextToSpeech(String text, ...) {
    textMain = text;
    ...
  }
}

Or you can have a setter method in order to set the value after object creation

public void setText(String text) {
  textMain = text;
}
Cimon
  • 399
  • 2
  • 11
1

Any time you are referencing a local variable in an anonymous class / lambda you need to declare that variable as final (immutable).

final String textMain = "text text";
textToSpeechSystem = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            speak(textMain); // textMain doesn't visible
        }
    }
});
-1

Thats because TextToSpeech.OnInitListener and textMain has different location in memory: TextToSpeech.OnInitListener is been located in the heap and available after current context will be closed, but textMain is been located in the stack and not available after current context will be closed.

To fix it. all you have to do is to move textMain to the heap.

final String textMain = "text text";
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
  • 1
    How does using final make it move to the heap? Even without the final keyword, the string object itself will be stored in the heap, which the reference will be stored on the stack. Using final makes sure that post variable capture, the value of the captured variable does not change. – Prashant Pandey Oct 18 '20 at 19:26