如何通过从Java单例调用kotlin活动方法解决错误?

问题描述:

我想调用此方法:

fun workingWithBtn(k: Int) {
        when (k) {
            1 -> {
                btn_submit_t.showError();
                Handler().postDelayed({
                    this@LoginScr.runOnUiThread {
                        btn_submit_t.hideLoading()
                        btn_submit_t.isEnabled
                    }
                }, 1000)
            }
            2 -> {
                btn_submit_t.showSuccess()
            }
            3 -> Handler().postDelayed({
                clickCount--
                this@LoginScr.runOnUiThread {
                    btn_submit_t.hideLoading()
                    btn_submit_t.isEnabled
                }
            }, 1000)
        }
    }

此方法放在基于kotlin的活动中,我想从Java单例调用它.我从单例这样调用此方法:

this method is placed at the kotlin-based activity and I would like to call it from java singleton. I call this method from singleton like this:

new LoginScr().workingWithBtn(3);

但是我收到错误消息:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference

据我了解,我的课程找不到我的按钮.我尝试使用findViewById,然后使用btn进行操作,但这并没有帮助我.我该如何解决这个问题?

as I understand my class can't find my button. I tried to use findViewById and then work with btn but it didn't help me. How I can solve this problem?

我已经设法通过BroadcastReceiver解决了我的问题.对于此解决方案,我们必须将单例添加到需要函数的地方,调用这些行:

I have managed to solve my problem via BroadcastReceiver. For this solution we have to add to our singleton to the place where we will need a function call these lines:

Intent intent = new Intent();
intent.setAction("btn_task"); // name of your filter
intent.putExtra("url", 1);
context.sendBroadcast(intent); // here you won't need context but I have to use it from singleton

然后我们在活动中创建一个变量:

then we create a variable at the activity:

lateinit var receiver: BroadcastReceiver

然后我们将分配值:

val filter = IntentFilter("btn_task") // we will filter all intents with our filter

然后我们必须创建并注册接收者:

and then we have to create and register our receiver:

receiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                workingWithBtn(intent.extras.getInt("url"))
            }
        }
registerReceiver(receiver, filter)

在活动将被销毁时删除接收者:

delete receiver when activity will be destroyed:

override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(receiver)
    }

也许会帮助别人.祝你好运:)

maybe it will help someone else. Good Luck :)