I am trying to call the startListening()
method from SpeechRecognizer
. I am calling the method from a class that is not directly linked from the MainActivity
layout, but extends Activity and is instantiated by the MainActivity
class. I understand what a null object reference is, however I don't see where the null object reference is coming from...
Here's the code:
public class VoiceRec extends Activity implements View.OnClickListener {
private String command;
private TextView outputText; //TODO:temporary for testing
private Button speakButton;
private SpeechRecognizer voicerecognizer;
private String packageName;
private RecognitionListener voiceRecListener = new RecognitionListener() {
@Override
public void onReadyForSpeech(Bundle params) {
Log.d("VoiceRec", "onReadyForSpeech");
}
@Override
public void onBeginningOfSpeech() {
Log.d("VoiceRec", "onBeginningOfSpeech");
}
@Override
public void onRmsChanged(float rmsdB) {
Log.d("VoiceRec", "onRmsChanged");
}
@Override
public void onBufferReceived(byte[] buffer) {
Log.d("VoiceRec", "onBufferReceived");
}
@Override
public void onEndOfSpeech() {
Log.d("VoiceRec", "onEndofSpeech");
}
@Override
public void onError(int error) {
Log.d("VoiceRec", "error " + error);
//mText.setText("error " + error);
}
@Override
public void onResults(Bundle results) {
ArrayList data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i = 0; i < data.size(); i++) {
Log.d("VoiceRec", "result " + data.get(i));
}
//mText.setText("results: " + str);
}
@Override
public void onPartialResults(Bundle partialResults) {
command = new String();
command = partialResults.getString(SpeechRecognizer.RESULTS_RECOGNITION);
outputText.setText(command);
}
@Override
public void onEvent(int eventType, Bundle params) {
Log.d("", "onEvent " + eventType);
}
};
public VoiceRec() {
voicerecognizer.setRecognitionListener(voiceRecListener);
}
//for testing with button and output only, remove later
public VoiceRec(Object...args) {
voicerecognizer = SpeechRecognizer.createSpeechRecognizer(this);
voicerecognizer.setRecognitionListener(voiceRecListener);
speakButton = (Button) args[0];
speakButton.setOnClickListener(this);
outputText = (TextView) args[1];
packageName = (String) args[2];
}
@Override
public void onClick(View v) {
Intent vrintent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
vrintent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
vrintent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, packageName);
vrintent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);
voicerecognizer.startListening(vrintent);
}
}
So the error occurs with the OnClick
method when I call voicerecognizer.startListening(vrintent)
. I had this method working when all the code was in the MainActivity
class originally, so I do not know how to fix this error. I assume it has to do something with context, but I am relatively new to this so any help would be appreciated!