ロジャー
ロジャー

Reputation: 357

onActivityResult is not triggered when startActivityForResult from a common method

I am writing an app which TV and phone layout uses different methods, and they share some common methods. I put the common methods into a separated class. Before I call the common method, "activity" is passed to the common class, and "startActivityForResult" is called from the common method. However, finish() does not trigger the onActivityResult() on the calling "Activity".

MainFragment.kt

class MainFragment : BrowseFragment() {
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        TVHandler.activity = activity
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        //not triggered    
    }
}

TVHandler.kt

import androidx.core.app.ActivityCompat.startActivityForResult
class TVHandler{
    fun play(item: Movie, extra_url: String = ""){    
                val intent = Intent(activity, PlaybackActivity::class.java)
                intent.putExtra("item", item)
                intent.putExtra("url", url)
                startActivityForResult(activity, intent, 0, null)
    }

    companion object {
        lateinit var activity: Activity
    }
}

PlaybackActivity.kt

class PlaybackActivity : FragmentActivity() {
    fun channelSwitch(direction: String, showMessage: Boolean){
        val intent = Intent()
        intent.putExtra("action", "switch")
        intent.putExtra("direction", direction)
        intent.putExtra("showMessage", showMessage)
        this.setResult(Activity.RESULT_OK, intent)
        finish()
    }
}

play() is called. Some action triggered ChannelSwitch(). However, onActivityResult() is not triggered. MainActivity is shown, without any error recorded. May I know how to modify it to make it work?

Upvotes: 0

Views: 814

Answers (1)

Bach Vu
Bach Vu

Reputation: 2348

Put onActivityResult in your activity that hosts the fragment so it can pass value to your fragment

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
}

Upvotes: 1

Related Questions