Reputation: 566
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/")
}
Upvotes: 16
Views: 22952
Reputation: 75645
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
Upvotes: 22
Reputation: 24
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"/>
Upvotes: 0
Reputation: 1100
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
Upvotes: 0
Reputation: 664
You can use late initialization - you don't have to make WebView nullable
lateinit var webView: WebView
Upvotes: 30