I am trying to call TextToSpeech in a different class. Here are what my classes look like right now:
//MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private SpeechRecognizer sr;
sr.setRecognitionListener(new Listener());
}
//Listener.java
public class Listener implements RecognitionListener() {
public void onResults(Bundle
MainActivity theMainActivity = new MainActivity();
//the following line always breaks the code:
tts = new TextToSpeech(theMainActivity, new TextToSpeech.OnInitListener() {/*...*/});
}
}
For context, the file in its context is on GitHub. The version on GitHub is the working version where everything is in MainActivity.java
, but I am attempting to move Listener
out into its own class Listener.java
.
The error received is java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ContentResolver android.content.Context.getContentResolver()' on a null object reference
.
Now for my long explanation of what I have tried...
What I've tried
When I tried replacing theMainActivity
with MainActivity.this
and get the error MainActivity is not an enclosing class
. I understood that I could either make Listener a static class (but won't compile), or I could instantiate new MainActivity().new Listener() (but won't compile).
Someone asked the exact same question here which itself is marked a duplicate. So my question is a duplicate of a duplicate... However there was no explicit answer given.
I understand that I'm supposed to somehow solve the NullPointerException. However, when I log the value right before usage it is not null at all. Instead theMainActivity
has value com.package.name.MainActivity@b76325e
in Log.d
. So if it's not null in the first place, yet throws a null error, how could it be fixed?
So I figured maybe it's Android-specific. After all, it has something to do with android ContentResolver... So I read this question and thought that creating an application context would work, except that my MainActivity extends AppCompactActivity instead of Application so I cannot write MainActivity.context.
I understand that I am missing out on some fundamental Java understanding. I get that there is an Application and Activity context for applications. I get that the problem has to do with getting context in Listener.java. I also get that somehow I need to bring the context into Listener.java. And I know that simply running new MainActivity()
in Listener.java is probably a bad idea because I should be using the original MainActivity Activity context which called onResults in the first place. The best solution I can think of is somehow making the context a 'global' in some way that can be accessed by any class, or something like that... but I keep running into pitfalls like "it's not static" and "no you can't call use android.content.Context because you're not using android.app.Application".
Any ideas?