Search code examples
androidspeech-to-textonactivityresult

How to check STT Result in an Android Fragment


I'm currently running an activity with a tabhost and 5 fragments:

Layout

Android API LVL19 Android Studio 2.2 Testing Device Samsung Galaxy Tab 3 with Android 4.4

On any of those fragments i have some edittext elements. I use a button per edittext to start androids Speech-To-Text prompt.

private void promptSTT() {
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
            getString(R.string.speech_prompt));
    startActivityForResult(intent, REQUEST_CODE_STT);
}

where private static final int REQUEST_CODE_STT = 250. The problem is, that the result is received by the activity. So i added in MyActivity.onActivityResult(...) a check for if(reqeustCode == REQUEST_CODE_STT) and start the ActiveFragment.onActivityResult(...) my problem is the android Speech-To-Text always returns some random requestCodes like 2555677 or 1233789 and others. So i can't detect if the result is actually from my fragment call. Can someone tell me why these random codes appear instead of the code I put in the call?

the onActivityResult simply checks the following:

    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
   {
     super.onActivityResult(requestCode, resultCode, data);
     if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_STT && data != null) {
       Fragment fragment = getSupportFragmentManager().getFragments()
                           .get(tabHost.getCurrentTab());
       fragment.onActivityResult(requestCode, resultCode, data);
     }
    }

Solution

  • As brandall suggested I looked into topics with "onActivityResult request code wrong fragment".

    There i found many explanations that always said the same.

    If you use onActivityResult() from a Fragment your Activitiy onActivityResult() gets the requestcode of the Fragment not the code you put in the startActivityForResult() that you started from a Fragment.

    So simply call getActivity().startActivityForResult(intent, requestcode).

    After reading that I tried it and works perfectly. It is really sad that this is not mentioned in the android developer guide.