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

This is the barcode scanning activity



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

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$
    at android.os.Handler.handleCallback(
    at android.os.Handler.dispatchMessage(
    at android.os.Looper.loop(
    at java.lang.reflect.Method.invoke(Native Method)

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 *