英文:
How to properly call a function from a private class?
问题
我有一个关于从另一个类调用函数的问题。
class MyActivity: AppCompatActivity()
{
override fun onCreate(savedInstanceState: Bundle?)
{...}
fun myFunction()
{...}
private class myAdapter (...) : BaseAdapter(), ListAdapter {
...
//一些代码
...
myFunction(); // <- 我应该如何正确调用它?
}
}
因为我遇到了这个错误:
java.lang.NullPointerException: 尝试在空对象引用上调用虚拟方法 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()'
我尝试调用 MainActivity().myFunction() 但结果一样。
英文:
I have an issue with calling a function from another class.
class MyActivity: AppCompatActivity()
{
override fun onCreate(savedInstanceState: Bundle?)
{...}
fun myFunction()
{...}
private class myAdapter (...) : BaseAdapter(), ListAdapter {
...
//some code
...
myFunction(); // <- How should I call it properly?
}
}
Because I'm getting this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
I tried calling it MainActivity().myFunction() but it does the same.
答案1
得分: 1
你的适配器应该是一个内部类。否则,它无法访问MainActivity的属性。
应该像这样:内部类myAdapter(...)
这可以解决你的问题,但不要采用这种方法,因为它违反了干净的代码和开闭原则。
英文:
Your adapter should be an inner class. Otherwise, it can not access the properties of MainActivity.
It should be like this: inner class myAdapter (...)
It can solve your problem but do not implement this approach as it's against clean code and the open-closed principle.
答案2
得分: 0
(context as MyActivity).myFunction()
:
实际上,我找到了我正在寻找的东西。我需要这样调用它:
英文:
Actually, I found what I was looking for. I need to call it like that:
(context as MyActivity).myFunction()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论