Search code examples
androidandroid-studiokotlintextview

Access a textview from another class file in kotlin


I create a textView with id ReceivedCodeTxt in activity_receive_code.xml file and then i create a new kotlin file with name SMSReceiver.kt ... Now i want to set text for a textView in my SMSReceiver.kt file but i dont know how to access it and change text from another class.

    val bundle = intent!!.extras
    try {
        if (bundle != null) {
            val pdusObj = bundle["pdus"] as Array<*>?
            for (i in pdusObj!!.indices) {
                val currentMessage = SmsMessage.createFromPdu(pdusObj[i] as ByteArray)
                val phoneNumber = currentMessage.displayOriginatingAddress
                val message = currentMessage.displayMessageBody
                Log.i("SmsReceiver", "senderNum: $phoneNumber; message: $message")
                // Show alert
                val toast = Toast.makeText(context,"senderNum: $phoneNumber, message: $message",Toast.LENGTH_LONG).show()

            } // end for loop
        } // bundle is null
    } catch (e: Exception) {
        Log.e("SmsReceiver", "Exception smsReceiver$e")
    }


}

}


Solution

  • You can do this by using interfaces

    create an interface in your SMSReceiver.kt class

    class SMSReceiver.kt(val callback:ICallback) {
        interface ICallback{
            fun updateUI(value:String)
        }
    
        fun doSomething() {
           // your operations to perform some task. then call this
           callback.updateUI(/*Pass your data which you want to set to your textview*/ "")
        }
    }
    
    
    class ActivityReceive: SMSReciever.ICallback {
    
        override fun updateUI(value:String) {
            //set the data which you got from SMSReceiver class
            textview.text = value
        }
    }