0

我有一个类可以进行蓝牙连接,并从连接在汽车中的 OBD 蓝牙加密狗获取 PID。但是当调用获取 RPM 的方法时,我有一个关于不初始化该属性的异常。

class BluetoothOBDManager : OBDManager {
    lateinit var context: Context
    private lateinit var input: InputStream
    private lateinit var output: OutputStream
    private lateinit var rpmCommand: RPMCommand
    private lateinit var coolantTempCommand: EngineCoolantTemperatureCommand
    private lateinit var airIntakeTempCommand: AirIntakeTemperatureCommand
    private lateinit var mmSocket : BluetoothSocket

    fun connect(deviceString: String) {
        var adapter: BluetoothAdapter = getDefaultAdapter()
        val device = adapter.getRemoteDevice(deviceString)
        val uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
        val mmSocket:BluetoothSocket=device.createRf....Record(uuid)

        mmSocket.let { socket ->
                socket.connect()
            }

        input = mmSocket.inputStream
        output = mmSocket.outputStream
        if (mmSocket.isConnected) {
            println("output.write =1")
            output.write(1)
        }
        rpmCommand = RPMCommand() //This is the INIT of the propert
    }

    override fun getCurrentRpm(): Int {
        rpmCommand.run(input, output) // This line throughs the EXCEPTION
        return rpmCommand.rpm
    }
}

这就是我从另一个类调用方法的方式

BluetoothOBDManager().connect(deviceString)
            var rpm  = BluetoothOBDManager().getCurrentRpm()
            rpmTextView.setText(rpm)

例外

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: gr.obd.logger, PID: 17486
    kotlin.UninitializedPropertyAccessException: lateinit property rpmCommand has not been initialized

我试图在方法内初始化属性,但没有运气

  override fun getCurrentRpm(): Int {
        rpmCommand = RPMCommand()
        rpmCommand.run(input, output) // This line throughs the EXCEPTION
        return rpmCommand.rpm
    }
4

1 回答 1

0
BluetoothOBDManager().connect(deviceString)
        var rpm  = BluetoothOBDManager().getCurrentRpm()

您的代码创建 a BluetoothOBDManager,连接它(初始化rpmCommand),然后将其丢弃,创建一个所有未初始化的 BluetoothOBDManager的并尝试调用getCurrentRpm它。应该是

val obdManager = BluetoothOBDManager()
obdManager.connect(deviceString)
val rpm = obdManager.getCurrentRpm()

这并不能解释为什么你会得到

我试图在方法内初始化属性,但没有运气

但这真的不应该发生;我预计会出现其他问题。

于 2019-09-05T12:28:07.777 回答