0

我制作了一个使用语音识别的安卓应用程序。问题是它显示空指针异常。

显示错误的代码是:

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)

4

1 回答 1

0

取自以下文档<T> T[] toArray(T[] a)

如果列表适合指定的数组并有剩余空间(即,数组的元素多于列表),则数组中紧随列表末尾的元素设置为空。

因此,如果您的r变量指向空列表,则数组的第一个元素将是null. 这会导致您的 NPE。您可以尝试验证列表的大小,但肯定是这样。

于 2012-04-18T08:37:35.443 回答