ArrayList.contains(“text”)抛出NullPointerException?

时间:2012-03-09 16:11:25

标签: java android arraylist nullpointerexception

我要尝试创建一个Android应用程序,我接受来自用户使用语音识别服务器的输入。我在ArrayList中捕获结果如下:

matches = data.getStringArrayListExtra(
                    RecognizerIntent.EXTRA_RESULTS);

匹配全局声明为:

ArrayList<string> matches;

现在我想检查用户是否说了特定的单词。所以我这样做:

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

但上面的行会抛出NullPointerException。

请帮忙。

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

5 个答案:

答案 0 :(得分:2)

显然,您的匹配为空。根据Intent文档,http://developer.android.com/reference/android/content/Intent.html#getStringArrayListExtra%28java.lang.String%29 如果在包中找不到密钥,则getStringArrayListExtra返回null。

在测试之前测试是否存在无效

答案 1 :(得分:1)

听起来似乎getStringArrayListExtra正在返回nullthe docs表示如果找到ArrayList值,则表示会这样做,所以当您尝试{{1}时它失败了,因为你试图取消引用空引用。在使用之前,您需要检查matches.contains("TextToBeDetected")的返回值,以确保它不是getStringArrayListExtra。 E.g:

null

答案 2 :(得分:1)

如果您看到文档Android.Content.Intent.GetStringArrayListExtra它说

  

以前使用putExtra()添加的项的值,如果未找到ArrayList值,则返回null。

在将列表设置为匹配之前,您需要检查列表为空。

答案 3 :(得分: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");
}

答案 4 :(得分:0)

data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)

将返回先前使用putExtra()添加的项的值,如果未找到ArrayList值,则返回null。在你的情况下,也许它返回null