我制作了一个使用语音识别的Android应用程序。问题是它显示了nullpointerexception。
显示错误的代码是:
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);
}
错误发生在第if(result[0].length()<=0)
行
答案 0 :(得分:0)
取自<T> T[] toArray(T[] a)
的文件:
如果列表适合指定的数组,并且有空余空间(即 数组中包含的元素多于列表中的元素 紧接在列表结尾之后设置为null。
因此,如果您的r
变量指向空列表,则数组的第一个元素将为null
。这导致你的NPE。您可以尝试验证列表的大小,但肯定是这种情况。