2012-03-09 52 views
-1

我想嘗試製作一個android應用程序,我接受用戶使用語音識別服務器的輸入。我捕捉如下的ArrayList中的結果:ArrayList.contains(「text」)引發NullPointerException?

matches = data.getStringArrayListExtra(
        RecognizerIntent.EXTRA_RESULTS); 

比賽是全局聲明:

ArrayList<string> matches; 

現在我要檢查,如果用戶已經說出一個特定的詞。所以我這樣做:

if(matches.contains("TextToBeDetected")) { } 

但線上方拋出一個NullPointerException。

請幫忙。

P.S是的,我是一個Java和Android新手。

+1

ArrayList 應該是ArrayList 。在你的getStringArrayListExtra方法中設置了什麼匹配? – smcg 2012-03-09 16:14:59

+0

@Selvin:我認爲你的意思是OP。對新手來說,這並不意味着什麼。 – 2012-03-09 17:09:22

回答

0

您確定matches已分配?
試試這個,看看你的logcat輸出:

if (matches == null) { 
    Log.d("YourAppName", "matches is null!"); 
} else if (matches.contains("TextToBeDetected")) { 
    Log.d("YourAppName", "matches does contain TextToBeDetected"); 
} else { 
    Log.d("YourAppName", "matches does not contain TextToBeDetected"); 
} 
+1

像這樣的評論(不解決PO的問題)應該添加爲評論,而不是答案。 – GETah 2012-03-09 16:15:53

+0

我想用戶可能想要一些測試代碼,因爲他/她提到他/他是一個新手。 – 2012-03-09 16:17:51

+0

這給你一個很好的理由,在評論中回答,而不是回答:) – GETah 2012-03-09 18:23:59

1

這聽起來好像getStringArrayListExtra將返回nullthe docs說,這將如果發現這樣的ArrayList值),所以當你嘗試matches.contains("TextToBeDetected")它失敗,因爲你試圖解引用一個空引用。在使用之前,您需要檢查getStringArrayListExtra的返回值以確保它不是null。例如: -

matches = data.getStringArrayListExtra(
        RecognizerIntent.EXTRA_RESULTS); 
// ... 
if (matches != null) { 
    if (matches.contains("TextToBeDetected")) { 
     // do something 
    } 
} 
0
​​

將返回()空,如果沒有ArrayList的價值發現與以前添加putExtra項目或價值。在你的情況下,也許它返回null

1

如果你看到的文檔Android.Content.Intent.GetStringArrayListExtra它說

先前與putExtra()或加入一個項目的null值,如果沒有ArrayList的值找到。

您需要先檢查列表是否爲空,然後再將其設置爲匹配。

相關問題