user1255273
user1255273

Reputation: 319

How do you populate an edittext field instead of a listview when using speech recognition?

I am using the code from google's sample voice recognition class. They write the top 5 results into a listview but I just want the top result posted in an edittext field. Is this possible? Or is it possible to populate the listview but then automatically copy the results to an edittext field?

Any help would be appreciated.

Upvotes: 1

Views: 996

Answers (2)

techexpertjc
techexpertjc

Reputation: 11

    public void doSome(View v) {
    Intent i=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
 RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    i.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak Up");
    i.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,1);
    startActivityForResult(i, 1111);


    //finish();
    //Toast.makeText(getApplicationContext(),"Anonymus class 1",Toast.LENGTH_LONG).show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    if(requestCode == 1111 && resultCode==RESULT_OK){

        ArrayList<String> results=data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
        String s=results.get(0);
        EditText ed=(EditText)findViewById(R.id.editText);
        ed.setText(s);

    }

i've used onclick attribute of the button but it doesn't matters this is working just fine in my case

Upvotes: 0

Sam Dozor
Sam Dozor

Reputation: 40734

If you only want 1 result back, you should specify it in the intent you use to start the Voice Recognition Activity:

private void startVoiceRecognitionActivity() {
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

    intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass().getPackage().getName());


    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    //since you only want one, only request 1
    intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);

    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");

    startActivityForResult(intent, 1234);
}

And then pull the single result and set it to your EditText:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK){
        //pull all of the matches
        ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

        String topResult = matches.get(0);
        EditText editText = findViewById(R.id.yourEditText);
        editText.setText(topResult);
    }
}

Upvotes: 2

Related Questions