Question

I am building an app which will be prompting the user to speak a few words and then comparing the words to a string and opening a new activity based on which string is spoken. The code I am using is this:

    package com.example.voiceex;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
    static final int check=1111;
    static String res;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button b1=(Button)findViewById(R.id.button1);
        b1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
                i.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say Something");
                startActivityForResult(i, check);
            }
        });
        /*if("hello".equalsIgnoreCase(res))
        {
            Toast.makeText(getBaseContext(), "Hello is spoken", Toast.LENGTH_SHORT).show();
        }
        else if("i am hungry".equalsIgnoreCase(res))
        {
            Toast.makeText(getBaseContext(), "Ill give you some food", Toast.LENGTH_LONG).show();
        }*/
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    protected void onActivityResult(int request,int result,Intent data)
    {
        if(request==check&&result==RESULT_OK)
        {
            res=data.getStringExtra(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
            Toast.makeText(getBaseContext(), res, Toast.LENGTH_SHORT).show();

        }
    }

}

The toast here is printed blank. And even the commented part is used, then also nothing happens. Where am i going wrong? Thanks

Was it helpful?

Solution

RecognizerIntent returns array of matches you should determine your self which string you want to use usually it is first one form array

ArrayList matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
for(String match : matches){
    Log.i("Matched text", match);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top