2012-04-18 114 views
0

我製作了一個使用語音識別的Android應用程序。問題是它顯示nullpointerexception。Android語音識別空指針異常

其示出了錯誤的代碼是:

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); 
} 

錯誤是來自的<T> T[] toArray(T[] a)文檔兩者的線if(result[0].length()<=0)

回答

0

發生:

如果列表在適合指定數組有空餘空間(即, 數組比列表中的元素多),數組中的元素緊接在列表結尾處的0被設置爲空。

因此,如果您的r變量指向空列表,則數組的第一個元素將是null。這導致你的NPE。您可以嘗試驗證列表的大小,但確實如此。

+0

感謝您的回覆。看到我發佈的應用程序安卓市場,我看到了這個錯誤。我嘗試了兩個錯誤修正,但失敗了。主要問題是r從語音識別引擎返回null。你能幫我一下嗎?? – 2012-04-18 08:41:53

+0

@HimanshuJaju遺憾地我沒有使用語音識別API,我只能指出你遇到的錯誤的原因。 – 2012-04-18 08:44:11

+0

順便說一句,如果我有10件事情在列表中,11可以存儲在我的數組,然後哪一個將爲空..? – 2012-04-18 08:45:29