android – Null-Pointer Exception when trying to access an EditText from another activity in Kotlin-ThrowExceptions

Exception or error:

EDIT : Solved by using startActivityForResult()

in Kotlin I am trying to set the content of an EditText of my main activity from within the HandleResult method of a barcode scanning activity, and I get a NPE. I have read https://kotlinlang.org/docs/tutorials/android-plugin.html

This is the barcode scanning activity

import kotlinx.android.synthetic.main.activity_main.*

...

override fun handleResult(rawResult: Result) {
    Toast.makeText(this, "Contents = " + rawResult.text +
            ", Format = " + rawResult.barcodeFormat.toString(), Toast.LENGTH_SHORT).show()
    doAsync {
        val url = "https://www.amazon.com/s/field-keywords=${rawResult.text}"
        val dom = Jsoup.connect(url).get()
        val title = dom.select("h2[class^=a-size-medium]")
        onComplete {
            txt_keyword.setText(title[0].text()) // <--- NPE crash
            onBackPressed()
        }
    }

The crash I get is

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
    at <mypackagename>.ScanActivity$handleResult$1$1.invoke(ScanActivity.kt:56)
    at <mypackagename>.ScanActivity$handleResult$1$1.invoke(ScanActivity.kt:20)
    at org.jetbrains.anko.AsyncKt$onComplete$1.run(Async.kt:57)
    at android.os.Handler.handleCallback(Handler.java:789)
    at android.os.Handler.dispatchMessage(Handler.java:98)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6940)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

When Ctrl+Entering on “txt_keyword”, I do jump to the relevant part of the activity_main.xml!

How to solve:

In android, you should not access the content of an activity from another activity, what you should do is have the handleResult() method in the main activity and use startActivityForResult() to start the Bar code activity then handle the result from the main activity or you could pass the content of the Edit Text from the from the main activity to the Bar Code activity through an Intent with a Bundle then handle the result in the BarCode activity.

Leave a Reply

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