Search code examples
androidkotlinandroid-intentfloating-action-button

How to send user to a search page using FAB in Kotlin, for Android Studio?


can anyone help me with this code?

p0.btnPlay.setOnClickListener {

    val songName = song.songName
    val songArtist = song.songArtist

    Toast.makeText(mCtx, "You clicked this button!", Toast.LENGTH_SHORT).show()

    val webIntent = Intent(Intent.ACTION_WEB_SEARCH, Uri.parse("https://www.youtube.com/results?search_query=$songArtist+$songName"))
    startActivity(webIntent)
}

I am getting an error at startActivity(webIntent) : Type mismatch: inferred type is Intent but Context was expected

How do I send a user to a youtube page like this? The toast message works fine, so the button click is connected to the XML.


Solution

  • If your mCtx is Activity context, then use

    try {
        val webIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/results?search_query=$songArtist+$songName"))
        mCtx.startActivity(webIntent)
    } catch(ex: Exception) {
        ex.stackTrace
    }
    

    If you are inside fragment then try using

    try {
        val webIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/results?search_query=$songArtist+$songName"))
        activity!!.startActivity(webIntent)
    } catch(ex: Exception) {
        ex.stackTrace
    }