Sergiusz Wasilewski
Sergiusz Wasilewski

Reputation: 1

How to pass a String variable to a new object in java

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.

Upvotes: 0

Views: 680

Answers (3)

user14410324
user14410324

Reputation:

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
        }
    }
});

Upvotes: 1

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

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";

Upvotes: -1

Cimon
Cimon

Reputation: 429

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;
}

Upvotes: 1

Related Questions