I am attempting to run the getByName method in my android app, but have found that doing so in the main activity is cause for concern. I know I need to use coroutines, or async, or threads. But I’m not sure how to go about this. I’m somewhat self-taught with the software so forgive any obvious errors.
”’
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val adr = getIpStr()
val serverAdr = "http://" + adr + ":5000"
val myWebView: WebView = findViewById(R.id.webView)
myWebView.webViewClient = WebViewClient()
myWebView.loadUrl(serverAdr)
}
fun goToSettings(view: View) {
val intent = Intent(this, SettingsActivity::class.java)
startActivity(intent)
}
private suspend fun getIpStr(): String? {
delay(2000L)
return getByName("raspberrypi").hostAddress
}
}
”’
2
Answers
You need to launch a coroutine using
lifecycleScope
:Alternatively, we can setup webview outside of
launch()
:You are getting exception because you starts your coroutine on main thread.
To perform network request,you need to use background thread .For that you can use " launch " coroutine builder with IO dispatcher to start new coroutine on background thread.