Hally
Hally

Reputation: 81

Android Kotlin java.lang.ClassCastException

When I run the code, I this Exception Exception

And this is the part that has problem. BTFragment

for every 60 seconds, it does function broadcastTEK, which is sending string generatedtek to other activity (AppCompatActivity()), which is BLEAdvertiser.

The code where it gets string generatedtek on BLEAdvertiser is below: BLEAdvertiser

So it is supposed to print received string on Logcat, but the app throws exception. Why is it? I have google searched about this exception, and some people say it happens because the variable type that I have sent doesn't match the type when I get the variable. But on my code, they are all String... What could be the problem?

Upvotes: 0

Views: 499

Answers (1)

Dharmender Manral
Dharmender Manral

Reputation: 1520

Try with the following code it will help you.

class TestActivity : AppCompatActivity(), BTFragment.BLEAdvertiser {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_test)

    //Make sure your BTFragment calling from this activity
}

override fun receiveData(encryptedtk: String) {
    toast(encryptedtk)
 }

}


class BTFragment : Fragment() {
private lateinit var  bleAdvertiser: BLEAdvertiser
override fun onAttach(context: Context) {
    super.onAttach(context)
    if (context is BLEAdvertiser) this.bleAdvertiser = context
}


fun broadcastTEk(text: String) {
 this.bleAdvertiser.receiveData(text)
}


interface BLEAdvertiser {
    fun receiveData(encryptedtk: String)
}
}

Upvotes: 1

Related Questions