16

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/")
}

4 Answers 4

30

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

lateinit var webView: WebView
Sign up to request clarification or add additional context in comments.

3 Comments

This is much better than accepted answer. Just don't access it before assigning it.
@RobCo it says Expecting member declaration
Also, This shows Property must be initialized or be abstract
22

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

2 Comments

it shows: Null can not be a value of a non-null type WebView
Why cant we use lateinit here?
0

for a global variable, this means it shouldn't be overridden accidentally , so you should instead lazyload it using kotlin's lazy which create the variable on the first call, other calls will just reference the lazy loaded variable

private val webview:WebView by lazy{
  findViewById<WebView>(R.id.webview)
}

That should come before the onCreate method

Comments

0

Below code worked for me:

val mywebviewURL = "https://www.google.com"

  override fun onStart() {
    super.onStart()

    events_webview.setWebViewClient(object : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            view?.loadUrl(url);
            return true
        }
    })
    events_webview.loadUrl(mywebviewURL)
}

Add internet permission to AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.