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

时间:2019-05-10 07:16:24

标签: java android 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单例调用它。我从单例这样调用此方法:

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一起使用,但没有帮助。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

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

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

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

lateinit var receiver: BroadcastReceiver

然后我们将分配值:

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

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

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

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

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

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