I have made an android app which uses speech recognition. The problem is that it shows nullpointerexception.
The code which shows the error is :
public void startVoiceRecognitionActivity()
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass().getPackage().getName());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Give Me An Order!");
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
/**
* Handle the results from the recognition activity.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
//store the result that the user might have said but google thinks he has said that only
ArrayList<String> r=data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String[] result = new String[r.size()];
result = r.toArray(result);
Intent i=new Intent(getApplicationContext(),search.class);
if(result[0].length()<=0)
{
showToast("Could not fetch command properly try again");
}
else
{
i.putExtra("q", result[0]);
startActivity(i);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
the error is occurring on the line if(result[0].length()<=0)
Taken from the documentation of
<T> T[] toArray(T[] a):Thus if your
rvariable points to empty list the first element of your array will benull. This is causing your NPE. You can try verifying the size of the list, but it is most certainly the case.