无法访问 kotlin 子 class 中的父 class 变量
Not able to access parent class variable in child class in kotlin
在科特林中,我试图在子 class 中使用父 class 变量,但我无法使用它们,因为我是科特林的新手,我不知道该怎么做只是
我正在尝试访问 sharedPerfernces 并获取但它给了我 null
class webViewActivity : AppCompatActivity{
internal var shared_preferences: SharedPreferences? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
shared_preferences = this.getPreferences(Context.MODE_PRIVATE)
mContext = this
}
class JavaScriptInterface(private val mContext: Context) {
@JavascriptInterface
fun exampleGet(path: String): String {
return webViewActivity().shared_preferences!!.getString(path, "")
//here shared_perferences is null
}
}
}
为什么我无法在子 class 中没有父 class 的构造函数的情况下访问父 class 变量。给我一些建议,不胜感激
在JavaScriptInterface
class前添加inner
。
就这样:
inner class JavaScriptInterface(private val mContext: Context) {
@JavascriptInterface
fun exampleGet(path: String): String {
return shared_preferences!!.getString(path, "")
}
}
在科特林中,我试图在子 class 中使用父 class 变量,但我无法使用它们,因为我是科特林的新手,我不知道该怎么做只是
我正在尝试访问 sharedPerfernces 并获取但它给了我 null
class webViewActivity : AppCompatActivity{
internal var shared_preferences: SharedPreferences? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
shared_preferences = this.getPreferences(Context.MODE_PRIVATE)
mContext = this
}
class JavaScriptInterface(private val mContext: Context) {
@JavascriptInterface
fun exampleGet(path: String): String {
return webViewActivity().shared_preferences!!.getString(path, "")
//here shared_perferences is null
}
}
}
为什么我无法在子 class 中没有父 class 的构造函数的情况下访问父 class 变量。给我一些建议,不胜感激
在JavaScriptInterface
class前添加inner
。
就这样:
inner class JavaScriptInterface(private val mContext: Context) {
@JavascriptInterface
fun exampleGet(path: String): String {
return shared_preferences!!.getString(path, "")
}
}