1

I have an AsyncTask to execute while trying to connect the phone to a Bluetooth device, I want to change an icon from a button if it connects successfully

(I'm new to Kotlin programming)

Main Code

enter image description here

I would be very grateful if anyone could help.

Sweta Jain
  • 3,248
  • 6
  • 30
  • 50

3 Answers3

1

Replace this with line 146 val blueBtn=this@MainActivity.findViewById(R.id.blue_btn)

Rahimian
  • 106
  • 1
  • 7
  • Still not working – Gaspar Pereira Jun 29 '22 at 23:01
  • 1
    create global button private lateinit var btn:Button and in oncreate{ btn=findViewById(R.id.blue_btn) } then you can use btn in your class or pass to class conectedtodevice private class ConnectToDevice(c:Context,btn:Button)... use btn btn.setOnclickListener(){ //click listener } – Rahimian Jun 29 '22 at 23:34
1

I would like to mention, that making changes from the async task is not really a best solution, since they are designed to handle only background jobs, so I would recommend sending a command from there to handle in the Activity

Still, if you want this, try changing you passed parameter context to be of type Activity, like context: Activity, and access findViewById by context.findViewById(...)

kboskin
  • 422
  • 3
  • 12
  • Can you explain a little more? (sorry for the question, but I'm starting programming in kotlin) – Gaspar Pereira Jun 29 '22 at 23:04
  • 1
    @GasparPereira async tasks are designed to make only background work without any access to the UI. Also, async tasks are deprecated and it's better to use services for background jobs, related article :https://medium.com/@varun93342/difference-between-thread-service-and-asynctask-in-android-d6e37960e56c So, I believe it would be beneficial if you could make your code to be like that 1. Async task handles only background job 2. Async task executes a callback to the activity https://stackoverflow.com/questions/9963691/android-asynctask-sending-callbacks-to-ui 3. Activity handles UI work – kboskin Jun 29 '22 at 23:35
0

Replace private to inner class.

Dhara Jani
  • 461
  • 3
  • 10