Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - Define variable globally for WebView

I'm trying to define a variable globally which is of the class WebView. In Android Java it could be easy done by writing the it

Java for global variable

 < ClassName > < variableName >

But in Kotlin I'm facing issue with its declaration.


class MainActivity : AppCompatActivity() {

var mywebview : WebView //<- This shows Property must be initialized or be abstract



override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
}

override fun onStart() {
    super.onStart()

    mywebview = findViewById(R.id.webViewGyrix) as WebView

    mywebview.setWebViewClient(object : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            view?.loadUrl(url);
            return true
        }
    } )
    mywebview.loadUrl("http://www.example.com/")
}
like image 840
Prateekro Avatar asked Apr 20 '17 13:04

Prateekro


2 Answers

You can use late initialization - you don't have to make WebView nullable

lateinit var webView: WebView
like image 137
Bruno Wieczorek Avatar answered Oct 09 '22 01:10

Bruno Wieczorek


This shows Property must be initialized or be abstract

Then initialize it i.e. to null. This is not a final value and you will be able to change it later:

var mywebview : WebView? = null

Alternatively, you can use lateinit feature of Kotlin, which would let you prevent having nullable mywebview if not needed:

lateinit var webView: WebView
like image 34
Marcin Orlowski Avatar answered Oct 09 '22 03:10

Marcin Orlowski