Downtips gives you a solution to Why the App crashing when using .setText – Kotlin in Android Studio.
This is not going to work. You can not instantiate an activity class like a regular class. Activities are specifically managed by the Android framework, which is responsible for their instantiation and lifecycle management
It’s best to update the text view inside the activity itself and ObjectDetectorHelper The class can just emit the string as Kotlin flow that the activity can subscribe
or you can use the objectDetectorListener
callback parameter of ObjectDetectorHelper
.
(Why App crashing when using .setText – Kotlin in Android Studio)
Here is the best solution.
Examples:
Using the objectDetectorListener
callback:
In ObjectDetectorHelper
//Move the ff to MainActivity
//if (results != null) {
// setMainActivity.textViewDetection.setText("pio")
// }
In MainActivity
override fun onCreate(savedInstanceState: Bundle?) {
//your other codes
val objectDetectorHelper = ObjectDetectorHelper(
context = this,
objectDetectorListener = object:DetectorListener{
override fun onResults(results, _, _, _){
if (results != null) {
textViewDetection.setText("your text")
}
}
override fun onError(error){}
}
)
}
Using Kotlin flow:
In ObjectDetectorHelper
val detectionTextStateFlow = MutableStateFlow<String>("")
//your other codes
if (results != null) {
detectionTextStateFlow.value = results[0].categories[0].label
}
In MainActivity
override fun onCreate(savedInstanceState: Bundle?) {
//your other codes
//should instantiate ObjectDetectorHelper before the following:
val objectDetectorHelper = ObjectDetectorHelper(context=this, objectDetectorListener = null)
lifeCyclecScope.launch{
objectDetectorHelper.detectionTextStateFlow
.flowWithLifecycle(lifecycle)
.collect{
textViewDetection.setText(it)
}
}
}
You can just remove the DetectorListener parameter if you don’t need it.
Why the target device does not come online in Android Studio