0

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?

1 Answer 1

1

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)
}
}
Sign up to request clarification or add additional context in comments.

3 Comments

Does it mean I have to create one new kotlin class named Test activity?
No, you need your MainActivity to implement BLEAdvertiser. At the moment this is not the case that's why the cast fails (when you do activity as BLEAdvertiser)
But in this case, isn't the encrytpedtek passed to MainActivity? I want to use the variable on BLEAdvertiser. If I have receiveData on MainActivity, how do I use that passed encrytpedtek in BLEAdvertiser?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.