Issue
I am trying to change my Variable inside my WebViewClient but my Function don't wait for page to load. I think It is because WebView has its own thread. If that is the case then how can I pause my function to wait for page. or is there any other method to keep the value in my Function?
private fun getNewUrl(url: String): String {
var newUrl = "null"
val webView = WebView(applicationContext)
webView.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
Toast.makeText(applicationContext, "Page Loaded", Toast.LENGTH_SHORT).show()
newUrl = url.toString()
}
}
webView.loadUrl(url)
return newUrl
}
Solution
Yes. Because that call happens Asynchronously. It doesn't block the execution of following lines.
So you need to have your listener class called when that result is loaded & use that result.
For example:
Create an interface:
interface OnPageLoadedListener {
fun onLoaded(url: String)
}
Pass it as an argument to your function:
private fun getNewUrl(url: String, onPageLoadedListener: OnPageLoadedListener) {
var newUrl: String
val webView = WebView(applicationContext)
webView.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
Toast.makeText(applicationContext, "Page Loaded", Toast.LENGTH_SHORT).show()
pageUrl = url.toString()
newUrl = url.toString()
onPageLoadedListener.onLoaded(newUrl)
}
}
webView.loadUrl(url)
}
Call your function:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
getNewUrl("https://www.google.com/", object : OnPageLoadedListener {
override fun onLoaded(url: String) {
Toast.makeText(applicationContext, url, Toast.LENGTH_SHORT).show()
}
})
}
Answered By - Mayur Gajra
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.