skip to Main Content

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


  1. You need to launch a coroutine using lifecycleScope:

    lifecycleScope.launch {
        val adr = getIpStr()
        val serverAdr = "http://" + adr + ":5000"
        val myWebView: WebView = findViewById(R.id.webView)
        myWebView.webViewClient = WebViewClient()
        myWebView.loadUrl(serverAdr)
    }
    

    Alternatively, we can setup webview outside of launch():

    val myWebView: WebView = findViewById(R.id.webView)
    myWebView.webViewClient = WebViewClient()
    
    lifecycleScope.launch {
        val adr = getIpStr()
        val serverAdr = "http://" + adr + ":5000"
        myWebView.loadUrl(serverAdr)
    }
    
    Login or Signup to reply.
  2. 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.

    lifecycleScope.launch(Dispatchers.IO) {
    val adr = getIpStr()
    val serverAdr = "http://" + adr + ":5000"
    //here switch to Main thread to Update your UI related task
    withContext(Dispatchers.Main){     
    myWebView.loadUrl(serverAdr)}
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search