androidspeech-recognitionrecognizer-intent

Android specific words speech recognition


I am trying to have the app recognize certain words said by the user using the code below, but for some reason it isn't working at all. Please review this and tell me what is wrong with it. Thank you

The app is simply suppose to display a toast message if the words "orange" or "apple" is said but nothing happens when using the code below.

//button onclick to trigger RecognizerIntent

public void OnClick_Speed_Detector(View v)
{
    Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    i.putExtra(RecognizerIntent.EXTRA_PROMPT, "speak up");
    startActivityForResult(i, 1);

}

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if(requestCode == 1 && resultCode == RESULT_OK)
    {
        ArrayList<String> result = 
                data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

                if(((result).equals("orange")))
                {
                  Toast.makeText(getApplicationContext(), "orange", Toast.LENGTH_LONG).show();

                }   
                else
                    if (((result).equals("apple")))
                { 
                  Toast.makeText(getApplicationContext(), "apple", Toast.LENGTH_LONG).show();   
                }

    }
}

Solution

  • Your issue is that you are testing if an ArrayList == a String, when it can't possibly (an ArrayList of type String contains multiple strings)

    Instead of:

    if ((result).equals("orange")) {}
    

    Try:

    if ((result).contains("orange")) {}
    

    This code will look through every index of the ArrayList and determine if any of the indexes of it equal "orange". If any do then it will return

    true
    

    ...and it will execute the if statement! Hope this helps!