Search code examples
androidspeech-recognitionspeech-to-text

How to remove square brackets [] from text getting from Speech To Text


Using Text To Speech in TextView appears recognition text in square brackets.

How to delete them?

For example: Instead of: car - [car]

 public class MainActivity extends AppCompatActivity implements View.OnClickListener {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button recognizeButton = (Button)findViewById(R.id.button1);
        recognizeButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "You may speak!");
        intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.ENGLISH);
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 1 && resultCode == RESULT_OK) {
            ArrayList<String> results;
            results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                TextView speechText = (TextView) findViewById(R.id.textView1);
                speechText.setText(results.toString());          
        }
    }
}

Solution

  • The results are returned as an ArrayList<String>. If you just want the first element of the returned list then fetch it by get(0), see more at http://developer.android.com/reference/java/util/ArrayList.html

    If you want to pretty-print the results but do not like the output of toString() then use e.g. join.