36

I am programming a speech recognition app in Kotlin for Android.

class MainActivity : AppCompatActivity() {
    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val intent:Intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
        startActivityForResult(intent, REQUEST_CODE)

    }

    override fun onActivityResult(requestCode:Int, resultCode:Int, data:Intent) {
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {/*do something*/  }
        super.onActivityResult(requestCode, resultCode, data)
    }
}

Strangly the compiler always finds the Error: 'onActivityResult' overrides nothing.

Documentation of Android states that result of startActivityForResult can be retrived with onActivityResult.

Now the question: how can one get the result of speech recognition using Kotlin?

Marcel Sonderegger
  • 772
  • 1
  • 8
  • 21

1 Answers1

93

Replace

override fun onActivityResult(requestCode:Int, resultCode:Int, data:Intent)

With below code, to make Intent object nullable.

override fun onActivityResult(requestCode:Int, resultCode:Int, data:Intent?)

As Intent is declared nullable in parent Activity class. Here is the sample code:

protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) 
Dhaval Patel
  • 10,119
  • 5
  • 43
  • 46
  • 3
    Just right now I noticed, that the [https://developer.android.com/training/camera/photobasics#kotlin] does it also wrong: forgetting the question mark after Intent. Was there some recent change in the library? – Marcel Sonderegger Oct 08 '18 at 19:17
  • 1
    They add more annotation to the framework to make it more convenient with Kotlin. But the doc, as usual does not update to the new code. – thuanle Jul 06 '19 at 08:43