Search code examples
androidkotlinandroid-intentandroid-activityonactivityresult

OnActivityResult method is deprecated, how do I use registerForActivityResult from a Menu's onOptionItemselected


I'm using Kotlin. I have beent trying to choose a folder to create a file in it and export Data from my Database into said file. But now it showed me, that startActivityForResult is deprecated

I have read the Question: OnActivityResult method is deprecated, what is the alternative? , but sadly, I couldn't see how you would implement that in a Optionsmenu, to open a Action_Create_Document for a Data-Export.

As a non-native Speaker, i also had quite a bit of trouble to understand the basic training: https://developer.android.com/training/basics/intents/result .
So my question is: How do you implement a call to choose a location and create a txt-file and the take said filelocation to fill it with text, with the registerForActivityResult without moving to another Activity/with staying on the Activity you are.

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
    return when (item.itemId) {
        R.id.Export -> {
            val intent = Intent(Intent.ACTION_CREATE_DOCUMENT)

            intent.addCategory(Intent.CATEGORY_OPENABLE)
            intent.type = "text/plain"
            intent.putExtra(Intent.EXTRA_TITLE, "Spells.txt")

            startActivityForResult(intent, 112)
            return true
        }
        else -> super.onOptionsItemSelected(item)
    }
}

    override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
    super.onActivityResult(requestCode, resultCode, resultData)
    if (requestCode == 112 && resultCode == RESULT_OK) {
        Toast.makeText(this, "Created", Toast.LENGTH_LONG).show()
        val path = resultData?.data?.path
        val myfile: File
        if (path != null) {
            myfile = File(path)
            ....
            doing stuff()
        }
    }
}

Solution

  • I have found the Problem in my thinking. I just had to use the Intent I created before to launch the resultLauncher, that was shown on the previous question, instead of the Activity-changing Intent.

    Also, I found, that the Value val resultLauncher, that was shown, had to be declared inside the class but outside the other functions, which was the part, where I got confused. Guess I got routine-blinded and should take more Breaks