android – Accessing data return by onActivityResult in onCreate function-ThrowExceptions

Exception or error:

In Android/Kotlin, I am launching a new activity with startActivityForResult in my onCreate function, and get the returned variable (let’s called it X) from onActivityResult outside of the onCreate function. Subsequently i want to access the variable X in the onCreate function to display it on the screen. However it never displays the data as if it were empty.

Any ideas of what I might be doing wrong? Thanks

Here is the code. When the user clicks on notesView it launches a new activity (Notes2Activity) where the user can enter its note in a full screen. Then upon validation of the note the code return to the previous activity where I am trying to edit the content of NotesView to returnNotes, but the app crashes.

override fun onCreate(savedInstanceState: Bundle?) 

val notesView: TextView
notesView = findViewById<TextView>(

notesView.setOnClickListener {
            val intent = Intent(this,

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {if (resultCode == Activity.RESULT_OK) {
            if(data != null) {
                val returnNotes: String = data.getSerializableExtra("notesEntered") as String
                var returnNotesInputs = returnNotes
                Log.d(TAG, "note returned to newContactActivity is: $returnNotes")}}
        else if (resultCode == Activity.RESULT_CANCELED) 
        {Log.d(TAG, "user clicked canceled in Notes2Activity")}
How to solve:

You can save the data in a global class field(s) and call recreate() on the activity after that. This will essentially call onCreate() again on the activity and then you can use the data in the fields.

IMO, this is a bad way to handle the situation. The specific logic from onCreate() can be exported to a private function. Then you can call this private function from onActivityResult() as well as onCreate().

Leave a Reply

Your email address will not be published. Required fields are marked *